首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将事件处理程序从祖级传递到Reactjs中的GrandChild组件

将事件处理程序从祖级传递到Reactjs中的GrandChild组件
EN

Stack Overflow用户
提问于 2016-09-01 01:29:00
回答 1查看 4.9K关注 0票数 4

我知道如何在React中将单击事件从父组件传递给子组件,但不知道如何在不使父组件可单击的情况下将其从祖父母传递给孙子组件。

在下面的示例中,我想让父div在单击孙子div时关闭。

这是我的代码,它不能工作。谢谢!

代码语言:javascript
复制
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')
);
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-09-01 01:48:05

看起来您需要将close方法作为道具传递给孙子组件(而不是包装它的div )。实际上,孙子没有this.props.close方法...

代码语言:javascript
复制
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;
        }
    }
});
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39255641

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档