![](/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.