【问题标题】:React 16.7 - React.SFC is now deprecatedReact 16.7 - React.SFC 现在已弃用
【发布时间】:2019-05-21 23:56:12
【问题描述】:

我用这样声明无状态组件:

const example: React.SFC<IExample> = ({propsType}) => ();

但是 SFC 现在已被弃用,也许 this twitter post from Dan Abramov 解释了原因。

既然 SFC 已被弃用,我们应该使用什么?

【问题讨论】:

  • 有趣的是,SFC 已被弃用,但 StatelessComponent 不是。但是,正如@Doğancan Arabacı 所说,应该使用FunctionComponent

标签: reactjs typescript deprecated deprecation-warning


【解决方案1】:

你应该使用React.FunctionComponentRename React's SFC to 'FunctionalComponent

此 PR 将 React.SFCReact.StatelessComponent 重命名为 React.FunctionComponent,同时为旧名称引入了已弃用的别名。

所以你的例子会变成:

const example: React.FunctionComponent<IExample> = ({propsType}) => ();

const example: React.FC<IExample> = ({propsType}) => ();

【讨论】:

    【解决方案2】:

    我会说接受的答案不再是最新的。

    React.FunctionComponent 有一定的缺点,as explained by the folks at create-react-app。他们的推理非常有说服力,我完全停止使用FC

    更好的选择:

    const example = ({ propsType }: IExample): JSX.Element => ();
    

    【讨论】:

    • 是和否。虽然您可能是对的,但问题是关于 React 16.7。我不知道更改标题的准则,因为未来的迭代又一次改变了。
    • 我最近才开始使用 react 仙女,所以我可能在这里遗漏了一些东西。但据我了解,FunctionComponent 类型从一开始就存在缺陷。隐式 children 不是较新的 React 版本的问题,或者是吗?
    • 不,我非常同意链接 PR 中所述的问题。很难做通用类型。根据文档,当时打字稿支持 React 16.7 中的处理方式。请记住,这是在钩子 (16.8) 之前 - 所以你只能在不需要状态、副作用或其他任何东西时使用 SFC/FC 等。主要仅用于视觉组件。
    猜你喜欢
    • 2021-10-10
    • 1970-01-01
    • 2015-03-13
    • 1970-01-01
    • 2016-07-19
    • 2019-04-16
    • 2019-05-31
    • 2019-02-07
    • 2022-12-31
    相关资源
    最近更新 更多