使用與之反應,我們再也不用打字稿,以便延長React.Props
讓編譯器知道,所有的反應成分的道具可以有孩子:如何在TypeScript中使用React無狀態功能組件的兒童?
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>
);
};
發出編譯錯誤:
Error:(102, 17) TS2339: Property 'children' does not exist on type 'MyProps'.
我想這是becau se真的沒有辦法讓編譯器知道在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中爲兒童使用無狀態功能組件?
謝謝!看來我在舊版本的類型不支持這個...我想是時候咬緊牙關了,用TS @ 2.0和'@types' – Aaron