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

sol*_*... 7 jsx reactjs

下面是将值从子组件传递到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;
Run Code Online (Sandbox Code Playgroud)

main.js

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

ReactDOM.render(<App/>, document.getElementById('app'));
Run Code Online (Sandbox Code Playgroud)

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

Dar*_*ght 12

您可以将更新功能传递给grand child 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'))
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)


Jos*_*gel 7

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

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

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