Reactjs - 如何将值从子组件传递到祖父组件?

时间:2016-12-13 12:55:03

标签: reactjs jsx

下面是将值从子组件传递到reactjs中的父组件的正确示例。

App.jsx

import React from 'react';

class App extends React.Component {

   constructor(props) {
      super(props);

      this.state = {
         data: 'Initial data...'
      }

      this.updateState = this.updateState.bind(this);
   };

   updateState() {
      this.setState({data: 'Data updated from the child component...'})
   }

   render() {
      return (
         <div>
            <Content myDataProp = {this.state.data} 
               updateStateProp = {this.updateState}></Content>
         </div>
      );
   }
}

class Content extends React.Component {

   render() {
      return (
         <div>
            <button onClick = {this.props.updateStateProp}>CLICK</button>
            <h3>{this.props.myDataProp}</h3>
         </div>
      );
   }
}

export default App;

main.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';

ReactDOM.render(<App/>, document.getElementById('app'));

我需要明确关于将值从子组件传递到祖父组件的概念。拜托,帮帮我。

2 个答案:

答案 0 :(得分:10)

您可以通过props将更新功能传递给大孩子,只需从子组件中再次传递它。

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      data: 'Initial data...'
    }
    this.updateState = this.updateState.bind(this);
  }

  updateState(who) {
    this.setState({data: `Data updated from ${who}`})
  }

  render() {
    return (
      <div>
        Parent: {this.state.data}
        <Child update={this.updateState}/>
      </div>
    )
  }
}

class Child extends React.Component {
  render() {
    return (
      <div>
        Child component
        <button onClick={() => this.props.update('child')}>
          CLICK
        </button>
        <GrandChild update={this.props.update}/>
      </div>
    );
  }
}

class GrandChild extends React.Component {
  render() {
    return (
      <div>
        Grand child component
        <button onClick={() => this.props.update('grand child')}>
          CLICK
        </button>
      </div>
    );
  }
}
ReactDOM.render(<App />, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

答案 1 :(得分:7)

最直接的方法是将updateState函数传递到树中,因为它们需要去。理想情况下,您的孙子组件被认为与祖父母组件完全分开......虽然这很快变得乏味。

这就是React Redux的用途。它使用发布/订阅模型创建全局状态对象。 (发布/订阅模型通过“连接”包装器稍微抽象出来。)您可以从任何地方向任何地方发送操作。动作触发“reducers”,它转换全局状态,React通过重新渲染组件(以惊人有效的方式)对修改后的状态作出反应。

对于小程序,Redux可能有点矫枉过正。如果您确实在模型中使用祖父/父/孙,只需传递updateState函数即可。随着程序的增长,请尝试使用Redux替换它们。它可能很难学习(特别是因为恕我直言,标准教程非常糟糕),但它是你所描述的一般问题的预期解决方案。