我已经使用 React 几个星期了,所以我还远不是专家。这就是问题所在:我正在构建一些布局其子组件的组件。也就是说,布局
可以如下使用:
var SomeComponent = React.createClass({
render: function () {
return (
<Layout>
<...child 1/>
<...child 2/>
...
</Layout>
);
}
});
嗯,Layout 不拥有子项,因此它无法修改它们的 props。它也不能克隆子级,因为它们可能包含引用。布局能否将每个子元素包装在(正确定位的)div 中?具有 ref 的子项会导致 SomeComponent ref 的正确更新吗?有更好的方法吗?
我对亲子沟通的普遍问题思考得更多一些,也比以前更困惑了。文档指出:
"For parent-child communication, simply pass props."
在文档的相关部分中,我们发现:
"In React, an owner is the component that sets the props of other components."
那么,什么给出了呢?在我看来,只有所有者,而不是 parent ,可以设置 Prop 。
这个问题已经在几篇文章中讨论过,但我没有找到令人满意的答案。一些答案建议克隆父级中的子级,但是如果原始所有者在其“所有者”中设置 ref 属性,我们就会遇到问题。在上面的示例中,SomeComponent 拥有作为子级传递给 Layout 的组件。如果我在布局中克隆子级(例如,添加回调),则布局将成为克隆的所有者,因此 SomeComponent 引用将无法获取它们。
我完全困惑了。
最佳答案
我不完全确定你在问什么,但有些东西是像你的 <Layout />
这样的包装组件可以对 child 做。
您提到您想将每个子组件包装在 div 中。这是一个例子:
var Layout = React.createClass({
render: function() {
var children = [];
if (this.props.children) {
for (var i=0; i < this.props.children.length; i++) {
var child = this.props.children[i];
children.push(
<div className="child-container">
{child}
</div>
);
}
}
return (
<div className="layout-container">
{children}
</div>
);
}
});
在上面您可以看到您可以访问 Layout
的子项在this.props.children
这只是一个子组件数组。因此,通过使用上面的简单 for 循环,或使用 this.props.children.map
您可以按照自己喜欢的方式包装每个子项并渲染它。
关于reactjs - 组件如何对其子组件进行布局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26317844/