2016-11-22 78 views
8

使用與之反應,我們再也不用打字稿,以便延長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中爲兒童使用無狀態功能組件?

回答

11

現在,你可以使用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贅述。

+0

謝謝!看來我在舊版本的類型不支持這個...我想是時候咬緊牙關了,用TS @ 2.0和'@types' – Aaron

相關問題