dan*_*mcr 3 javascript components jsx reactjs
所以我想从我的顶级组件通过一些道具,一个子组件,我做了一些网上搜索,但无法找到任何东西,显示了如何可以通过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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
当我在下一个组件中调用"数据"道具时:
家(孩子):
//ON COMPONENT RENDER
componentDidMount = () => {
console.log("home");
console.log(this.props.data);
}
Run Code Online (Sandbox Code Playgroud)
在我的控制台中它返回:
家
未定义
有关我应该如何使用这个的任何指示?感谢任何帮助,谢谢你提前.
如果你试图直接向孩子们添加一个道具,那么这不会真正起作用,因为组件是不可变的.你应该做的是创建一个包含孩子克隆的地图.
这篇博文的解释相当不错: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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6263 次 |
| 最近记录: |