我知道如何在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')
);发布于 2016-09-01 01:48:05
看起来您需要将close方法作为道具传递给孙子组件(而不是包装它的div )。实际上,孙子没有this.props.close方法...
var Parent = React.createClass({
render() {
var parentBoxStyle = {backgroundColor: 'red', height: 100, width: 100};
if (this.props.open == true) {
return <div style={parentBoxStyle}>
<Grandchild close={this.props.close} />
</div>
}
else {
return null;
}
}
});https://stackoverflow.com/questions/39255641
复制相似问题