【发布时间】:2021-08-04 10:21:48
【问题描述】:
我正在使用功能组件。我已经构建了我的独立组件并将它们放入我的index.js 文件中。
现在组件的结构是(伪代码):
<App stateVariable1={x} stateVariable2={y} stateVariable3={z}>
<ChildOne props1={x} props2={y} />
<ChildTwo props1={z}/>
</App>
ChildOne 和 ChildTwo 目前在 App.js 内呈现,因此将状态变量传递给两个孩子非常容易。
我想将渲染后的子元素提取到index.js 中,并用App.js 中的{props.children} 替换两个子元素,以增加组件的SRP 并使其更具可重用性。
但是,我很难理解如何在我的 index.js 文件中将多个状态变量作为多个 props 传递给 props.children。
我已经阅读了 Render Props 的 react 文档,其中涉及将一个 prop 传递给单个子级,而不是多个想要接收不同 props 的子级。
我该如何实现我想做的事情?
更新
我已尝试按照此处接受的答案使用渲染道具:How to pass props to {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 中定义。
我哪里错了?
更新 2:解决方案
我将所有状态变量作为参数传递给渲染道具,这解决了问题:
ReactDOM.render(
<React.StrictMode>
<App>
{(stateVariable1, stateVariable2, stateVariable3) => (
<Fragment>
<ChildOne props1={stateVariable1} props2={stateVariable2} />
<ChildTwo props3={stateVariable3} />
</Fragment>
)}
</App>{' '}
</React.StrictMode>,
document.getElementById('root')
);
有没有办法解构它,这样我就不需要将每个参数传递给回调?我正在使用功能组件,因此状态存储在多个变量中,而不是在类组件的状态对象中。
【问题讨论】:
-
你有效地回答了你自己的问题:D。您仍然可以使用
useState({ stateVar1: ..., stateVar2: ... })将它们作为道具对象传递,但请注意,您需要将 App.js 中的对象替换为新对象,否则不会检测到更改。在你的孩子作为一个功能,你可以这样做:({ stateVar1, ...otherVars }) => (<><ChildOne stateVar1={stateVar1}/><ChildTwo {...otherVars} /></>) -
@Tyblitz 谢谢,我应该在哪里使用
useState函数? -
@Tyblitz 它按上述方式工作,现在不行,我收到错误消息:
Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it. -
抱歉,我认为
useState显然在App.js中。您的错误似乎是您忘记在app.js中调用props.children(stateVars)。
标签: javascript reactjs