我了解如何在 React 中将单击事件从父组件传递给子组件,但不明白如何在不使父组件可点击的情况下将其从祖父组件传递给孙子组件。
在以下示例中,我希望父 div 在单击孙子 div 时关闭。
这是我的代码,它不起作用。谢谢!
var Grandparent = React.createClass({
getInitialState: function() {
return {open: true};
},
close: function() {
this.setState({open: false});
},
render() {
var grandparentBox={backgroundColor: 'yellow', height: 400, width: 400};
return <div style = {grandparentBox}><Parent open={this.state.open} close = {this.close}/></div>;
}
});
var Parent = React.createClass({
render() {
var parentBox={backgroundColor: 'red', height: 100, width: 100};
if (this.props.open == true) {
return <div close={this.props.close} style = {parentBox}><Grandchild/></div>
}
else {
return null;
}
}
});
var Grandchild = React.createClass({
render() {
var grandchildBox={backgroundColor: 'black', height: 20, width: 20, top: 0};
return <div onClick={this.props.close} style = {grandchildBox}></div>
}
});
ReactDOM.render(
<Grandparent/>,
document.getElementById('container')
);