【问题标题】:Passing Event Handler From Grandparent to GrandChild Component in Reactjs在 Reactjs 中将事件处理程序从祖父母传递给 GrandChild 组件
【发布时间】:2016-08-31 17:28:59
【问题描述】:

我了解如何在 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')
);

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    看起来您需要将 close 方法作为道具传递给 Grandchild 组件(而不是包装它的 div)。事实上,Grandchild 没有方法 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;
            }
        }
    });
    

    【讨论】:

    • 谢谢!但是,如果我将关闭方法传递给 Grandchild,它不会对 onClick 做任何事情。
    • 我不确定您要查找的确切内容,但单击孙子会关闭此fiddle 中的孙子和父级。
    • 谢谢乍得,问题是我只希望孙子能够处理点击。当您单击父项时,它不应该关闭,但是当您单击孙子项时,两者都应该关闭。
    • 好的,这就是我认为你想要的。您是否在我上面链接的小提琴中尝试过?我点击红色和黄色区域,没有任何反应。然后我点击黑框,黑色和红色都关闭。您还在寻找其他东西吗?
    • 哦,我没看到 - 谢谢乍得!有效!:)
    猜你喜欢
    • 1970-01-01
    • 2017-04-28
    • 2018-09-26
    • 2015-11-18
    • 2022-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多