Skip to main content

ADR006避免使用 React.FC 和 React.SFC

上下文

Facebook 已删除React.FC原因是我们发现这是一个不必要的功能,几乎没有任何益处,而且还有一些缺点。

主要原因是

  • 隐式添加了 子代道具 子代不支持通用类型

如需了解更多有关搬迁的信息,请参阅此公关.

决定

为了使我们的代码库保持最新,我们决定React.FCReact.SFC在我们的代码库中添加新代码时,应避免使用"......"。

下面就是一个例子:

/* Avoid this: */
type BadProps = { text: string };
const BadComponent: FC<BadProps> = ({ text, children }) => (
<div>
<div>{text}</div>
{children}
</div>
);

/* Do this instead: */
type GoodProps = { text: string; children?: React.ReactNode };
const GoodComponent = ({ text, children }: GoodProps) => (
<div>
<div>{text}</div>
{children}
</div>
);

/* Or as a shorthand, if no specific child type is required */
type GoodProps = PropsWithChildren<{ text: string }>;
const GoodComponent = ({ text, children }: GoodProps) => (
<div>
<div>{text}</div>
{children}
</div>
);

后果

我们将逐步取消目前使用的React.FCReact.SFC从我们的代码库中删除。