簡體   English   中英

Reactjs - 如何將值從子組件傳遞到祖父組件?

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

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

我需要明確關於將值從子組件傳遞到祖父組件的概念。 請幫我解決這個問題!!

您可以通過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 通過重新渲染組件(以一種非常有效的方式)對修改后的狀態做出反應。

對於小程序,Redux 可能有點矯枉過正。 如果您的模型中確實只有祖父母/父母/孫子女,只需傳遞 updateState 函數即可。 隨着程序的增長,嘗試用 Redux 替換它們。 它可能很難學習(尤其是因為恕我直言,標准教程簡直太糟糕了),但它是您所描述的一般問題的預期解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM