我超级坚持某事 . 虽然我理解父母如何将道具传递给孩子,但我无法弄清楚如何使用孩子与父母,祖父母等进行沟通 .
基本上,我有一个嵌套组件的子项,我想这样做,以便在单击此子组件时,另一个子项呈现与父级相同的级别 .
这是我的代码......
var Grandparent = React.createClass({
getInitialState: function() {
return {closed: true};
},
checkMenuState: function() {
if (this.state.closed == true) {
return;
}
else {
return <Child/>;
}
},
handleState: function() {
this.setState({closed: false});
{this.checkMenuState}
},
render: function() {
return <div><Parent/>{this.checkMenuState()}<OtherChild onClick={this.handleState}/></div>
}
})
var Parent = React.createClass({
render: function() {
var parentSquare={backgroundColor: 'blue', height: 400, width: 400};
return <div style={parentSquare}></div>;
}
});
var Child = React.createClass({
render: function() {
var childSquare={backgroundColor: 'orange', height: 100, width: 100, top: 0, position: 'absolute'};
return <div style={childSquare} closed={this.props.closed}></div>
}
});
var OtherChild = React.createClass({
render: function() {
var childSquare={backgroundColor: 'yellow', height: 100, width: 100, top: 100, position: 'absolute'};
return <div style={childSquare}></div>
}
});
ReactDOM.render(
<Grandparent/>,
document.getElementById('container')
);
因此,在初始渲染时,页面应如下所示:
然后,一旦点击黄色div,它应该如下所示:
截至目前,点击时没有任何事情发生 . 这是我的JSFiddle的链接:JSFiddle
1 回答
为了让您的孩子修改其父级的状态,您应该从父级向子级传递一个闭包(一种可以访问另一个范围的方法) . 请注意,您所谓的“父”不是真正的父级(:''(),而是您的子组件的兄弟 . 只有祖父母有内部组件 .
Give it a try!