![](/img/trans.png)
[英]React.cloneElement: pass new children or copy props.children?
[英]React pass x state variables to y {props.children}
我正在使用功能組件。 我已經構建了單獨的組件並將它們放入我的index.js
文件中。
現在組件的結構是(偽代碼):
<App stateVariable1={x} stateVariable2={y} stateVariable3={z}>
<ChildOne props1={x} props2={y} />
<ChildTwo props1={z}/>
</App>
ChildOne 和 ChildTwo 目前在App.js
中呈現,因此將 state 變量傳遞給兩個孩子非常容易。
我想將渲染的子元素提取到index.js
中,並將兩個子元素替換為 App.js 中的 { App.js
} ,以增加組件的 SRP 並使其更具可重用性。
但是,我很難理解如何將多個 state 變量作為多個道具傳遞給我的index.js
文件中的props.children
。
我已經閱讀了 Render Props 的 react 文檔,其中處理了一個道具被傳遞給一個孩子,而不是多個想要接收不同道具的孩子。
我如何 go 關於實現我想做的事情?
我已嘗試按照此處接受的答案使用渲染道具: 如何將道具傳遞給 {this.props.children}
我的index.js
看起來像這樣:
ReactDOM.render(
<React.StrictMode>
<App>
{(stateVariable1) => (
<Fragment>
<ChildOne props1={stateVariable1} props2={stateVariable2} />
<ChildTwo props3={stateVariable3} />
</Fragment>
)}
</App>{' '}
</React.StrictMode>,
document.getElementById('root')
);
然而,所有的 props/stateVariables 都存在未定義的錯誤,因為它們當然沒有在index.js
中定義。
我哪里錯了?
我將所有 state 變量作為 arguments 傳遞給渲染道具,這解決了問題:
ReactDOM.render(
<React.StrictMode>
<App>
{(stateVariable1, stateVariable2, stateVariable3) => (
<Fragment>
<ChildOne props1={stateVariable1} props2={stateVariable2} />
<ChildTwo props3={stateVariable3} />
</Fragment>
)}
</App>{' '}
</React.StrictMode>,
document.getElementById('root')
);
有沒有辦法解構它,這樣我就不需要將每個參數傳遞給回調? 我正在使用功能組件,因此 state 存儲在多個變量中,而不是存儲在 class 組件的 state ZA8CFDE63311BD59EB2AC96B8 中。
我認為您可以避免完全使用props.children
。
如果您有如下結構,您的SRP原則仍然適用。
以上幾行的意思是,您可以將Child1
和Child2
作為App
組件中的組件,而不是使用 render props 模式或props.children
。
就像是
const App = (props) => {
return (
<>
<Child1 {...props} />
<Child2 {...props} />
</>
);
}
如果您想讓代碼更通用並擁有一個Children
組件,您可以將所有子組件提取到index.js
文件中,以便您的App
組件保持不變,但老實說可能不需要這樣做。
我在 Tyblitz 的幫助下解決了我的問題。
ReactDOM.render(
<React.StrictMode>
<App>
{({stateVar1, stateVar2, ...stateVars}) => (
<Fragment>
<ChildOne props1={stateVar1} props2={stateVar2} />
<ChildTwo {...stateVars} />
</Fragment>
)}
</App>{' '}
</React.StrictMode>,
document.getElementById('root')
);
然后,我將useState()
function 添加到我的App
組件,並將所有 state 變量作為 object 傳遞。
最后,我將這個新的 state 變量作為參數傳遞給我的返回調用:
return <div className='App'>{props.children(stateVars)}</div>;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.