使用带有React的TypeScript,我们不再需要扩展React.Props,以便编译器知道所有的反应组件道具都可以有子代:
interface MyProps { }
class MyComponent extends React.Component<MyProps, {}> {
public render(): JSX.Element {
return <div>{this.props.children}</div>;
}
}
Run Code Online (Sandbox Code Playgroud)
但是,无状态功能组件似乎不是这样的:
const MyStatelessComponent = (props: MyProps) => {
return (
<div>{props.children}</div>
);
};
Run Code Online (Sandbox Code Playgroud)
发出编译错误:
错误:(102,17)TS2339:"MyProps"类型中不存在属性"children".
我想这是因为编译器真的没办法知道children在props参数中会给出一个vanilla函数.
所以问题是我们应该如何在TypeScript中使用无状态功能组件中的子项?
我可以回到以前的方式MyProps extends React.Props,但Props界面被标记为已弃用,无状态组件没有或支持Props.ref我理解它.
所以我可以children手动定义道具:
interface MyProps {
children?: React.ReactNode;
}
Run Code Online (Sandbox Code Playgroud)
第一:是ReactNode正确的类型?
第二:我必须将子项写为optional(?),否则消费者会认为它children应该是component()的属性,<MyStatelessComponent children={} />如果没有提供值,则会引发错误.
好像我错过了一些东西.任何人都可以清楚地说明我的最后一个例子是否是在React中使用无子功能组件和子项的方法?
我正在使用带有打字稿的反应。我有一个返回 jsx 中的组件的函数:
function TestComponent(str: string) {
return <span>Hello, your string was {str}</span>
}
Run Code Online (Sandbox Code Playgroud)
假设该函数是合理的(是吗?),我如何在更多 jsx 代码中调用它?
我努力了:
<TestComponent str="abcde" />
<TestComponent str={'abcde'} />
<TestComponent {'abcde'} />
<TestComponent {str:'abcde'} />
Run Code Online (Sandbox Code Playgroud)
但我怀疑我错过了一些关于函数参数如何传递的更基本的东西(我对反应和打字稿都很陌生)。
谢谢。