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

Reactjs - How to pass values from child component to grand-parent component?

下面是在 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'));

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

你可以通过props把update函数传给grand child,从子组件再传一遍就可以了。

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>

最直接的方法是将 updateState 函数尽可能向下传递到树中需要的位置。理想情况下,您的孙子组件被认为与祖父组件完全分开......尽管这很快就会变得乏味。

这就是 React Redux 的用途。它使用 publish/subscribe 模型创建一个全局状态对象。 (publish/subscribe 模型通过 "connect" 包装器进行了某种程度的抽象。)您可以从任何地方向任何地方发送操作。动作触发 "reducers",它转换全局状态,React 通过重新渲染组件(以一种非常有效的方式)对修改后的状态做出反应。

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