所以我试图将一些 props 从我的顶级组件传递到子组件,我在网上做了一些搜索,但找不到任何显示我如何通过 WITH 传递 this.props.children 的东西一些值我的组件的状态。这是我的代码。
布局(父级):
export default class Layout extends React.Component {
constructor (props) {
super(props)
this.state = { data: 'test' }
}
render() {
const {location} = this.props;
console.log("layout");
return (
<div>
<Nav location={location}/>
<div className="container">
<div className="row">
<div className="col-lg-12">
{this.props.children}, data={this.state.data}
</div>
</div>
<Footer/>
</div>
</div>
);
}
}
当我在下一个组件中调用“数据” Prop 时:
家( child ):
//ON COMPONENT RENDER
componentDidMount = () => {
console.log("home");
console.log(this.props.data);
}
在我的控制台中它返回:
home
Undefined
关于我应该如何兴奋剂的任何指示?感谢您提供任何帮助,在此先感谢您。
最佳答案
如果您试图直接向子组件添加 Prop ,这将不会真正起作用,因为组件被认为是不可变的。相反,您应该做的是创建一个包含子项克隆的 map 。
这篇博文解释得相当好:http://jaketrent.com/post/send-props-to-children-react/
以及为您的代码更改的相关代码片段:
class Layout extends React.Component {
constructor (props) {
super(props)
this.state = { data: 'test' }
}
renderChildren() {
return React.Children.map(this.props.children, child => {
if (child.type === Child) {
return React.cloneElement(child, {
data: this.props.data
})
} else {
return child
}
});
}
render() {
const {location} = this.props;
console.log("layout");
return (
<div>
<Nav location={location}/>
<div className="container">
<div className="row">
<div className="col-lg-12">
{this.renderChildren()}
</div>
</div>
<Footer/>
</div>
</div>
);
}
}
关于javascript - React - 使用 this.props.children 传递状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42231074/