React 渲染屬性

學習如何使用渲染屬性來構建 React 應用程序 一個常見的模式用於在組件間共享狀態是使用 children 屬性。 在組件的 JSX 中,你可以渲染 {this.props.children} ,它會自動將父組件中傳遞的任何 JSX 插入為子元素: class Parent extends React.Component { constructor(props) { super(props) this.state = { /*...*/ } } render() { return <div>{this.props.children}</div> } } const Children1 = () => {} const Children2 = () => {} const App = () => ( <Parent> <Children1 /> <Children2 /> </Parent> ) 然而,這裡存在一個問題:無法從子元素中訪問父組件的狀態。 為了能夠共享狀態,你需要使用一個渲染屬性組件,而不是將組件作為父組件的子元素傳遞。你需要傳遞一個函數,在 {this.props.children()} 中執行該函數。該函數可以接受參數: class Parent extends React.Component { constructor(props) { super(props) this....