将TypeScript与React结合使用,我们不再需要扩展React.Props以使编译器知道所有react组件prop都可以有子代:
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参数中将提供香草函数。
所以问题是我们应该如何在TypeScript的无状态功能组件中使用子代?
我可以回到的旧方法MyProps extends React.Props,但是该Props接口被标记为已弃用,并且Props.ref据我所知,无状态组件不具有或不支持。
所以我可以children手动定义道具:
interface MyProps {
children?: React.ReactNode;
}
第一:是ReactNode正确的类型吗?
第二:我必须将子级写为可选(?),否则消费者会认为这children应该是组件()的属性,<MyStatelessComponent children={} />如果未提供值,则会引发错误。
好像我缺少什么。谁能说清楚我的最后一个示例是否是在React中对子级使用无状态功能组件的方法?
@types