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

IT技术 javascript reactjs jsx
2021-05-05 07:56:39

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

应用程序.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;

主文件

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

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

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

2个回答

您可以通过 将更新函数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>

最直接的方法是将 updateState 函数传递到树的最深处。理想情况下,您的孙组件被认为与祖父组件完全分开……尽管这很快就会变得乏味。

这就是React Redux的用途。它使用发布/订阅模型创建一个全局状态对象。(发布/订阅模型通过“连接”包装器在某种程度上抽象化了。)您可以从任何地方向任何地方分派动作。Actions 触发“reducers”,它改变全局状态,而 React 通过重新渲染组件(以一种非常有效的方式)对修改后的状态做出react。

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