首页 文章

如何在TypeScript中使用具有React无状态功能组件的子项?

提问于
浏览
13

使用带有React的TypeScript,我们不再需要扩展 React.Props ,以便编译器知道所有的反应组件道具都可以有子代:

interface MyProps { }

class MyComponent extends React.Component<MyProps, {}> {
  public render(): JSX.Element {
    return <div>{this.props.children}</div>;
  }
}

但是,无状态功能组件似乎不是这样的:

const MyStatelessComponent = (props: MyProps) => {
  return (
    <div>{props.children}</div>
  );
};

发出编译错误:

错误:(102,17)TS2339:“MyProps”类型中不存在属性“children” .

我想这是因为编译器确实没有办法知道在props参数中将给出一个vanilla函数 children .

所以问题是我们应该如何在TypeScript中使用无状态功能组件中的子项?

我可以回到 MyProps extends React.Props 的旧方式,但 Props 接口是marked as deprecated,无状态组件没有或支持 Props.ref ,据我所知 .

所以我可以手动定义 children 道具:

interface MyProps {
  children?: React.ReactNode;
}

第一:是 ReactNode 正确的类型?

第二:我必须将子项写为可选项( ? ),否则消费者会认为 children 应该是组件的属性( <MyStatelessComponent children={} /> ),如果没有提供值,则会引发错误 .

好像我错过了一些东西 . 任何人都可以清楚地说明我的最后一个例子是否是在React中使用带无子功能组件的方式?

1 回答

  • 18

    现在,您可以使用 React.StatelessComponent<> 类型,如下所示:

    const MyStatelessComponent : React.StatelessComponent<{}> = props =>
        <div>{props.children}</div>
    

    我添加的内容是将组件的返回类型设置为 React.StatelessComponent 类型 .

    对于具有您自己的自定义道具的组件(如 MyProps 接口):

    const MyStatelessComponent : React.StatelessComponent<MyProps> = props =>
        <div>
            <p>{props.propInMyProps}</p>
            <p>{props.children}</p>
        </div>
    

    现在, props 已经获得 children 属性以及来自 MyProps 接口的属性 .

    我在打字稿版本2.0.7中检查了这个

    此外,为简洁起见,您可以使用 React.SFC 而不是 React.StatelessComponent .

相关问题