reactjs - 在 Reactjs 中将事件处理程序从祖 parent 传递到孙子组件

标签 reactjs

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

最佳答案

看起来您需要将 close 方法作为 prop 传递给 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;
        }
    }
});

关于reactjs - 在 Reactjs 中将事件处理程序从祖 parent 传递到孙子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39255641/

相关文章:

reactjs - create-react-app with --template typescript 不创建 .tsx 文件

javascript - 在React JSX内部循环

reactjs - 通过 Ref 创建 React Portal

javascript - 如何传递子 DOM 节点来 react 样式组件

javascript - React 网格布局 - 具有添加/删除小部件的本地存储

reactjs - Material 表添加行位置

javascript - 无法重置表单输入字段(React JS 控制组件)

javascript - 在 React 中处理多个输入

express - 为什么我们需要在express.js服务器上使用代理才能获得与react-routing相结合的webpack热重载服务器功能

reactjs - 如何使用map和join渲染React组件?