【问题标题】:react.js props and state inside multilevel components多级组件中的 react.js 道具和状态
【发布时间】:2017-01-17 07:55:42
【问题描述】:

我有一个具有如下组件结构的应用程序。 Component App Main parent,它使用 {this.props.children} 在所有组件中加载标题 组件头 组件主页 组件仪表板 组件数据 组件数据加载

App 在渲染中包含 Header 并传递一些状态变量。 Home 包含 Dashboard,其中包含更新 App 的状态变量以更新 Header 的操作。 数据包含DataLoad也从这里我需要更新App的状态变量来更新Header。

For example my App is like
import React from 'react';
import Header from './Header.jsx';
class App extends React.Component {
constructor(props) {
  super();
  this.state = {
                show : '1',
            }
   this.showHide = this.showHide.bind(this);
}

showHideSearch() {
    this.setState(prevState => ({
      show: prevState.show == '1' ? '0' : '1',
    }));
}
render() {
return (
    <div>
        <Header show={this.state.show}/>
        {this.props.children}
    </div>
)
}  
}

export default App;

import React from 'react';
import Dashboard from './Dashboard.jsx'
class Home extends React.Component {
constructor(props) {
  super();
  this.showHide = this.showHide.bind(this);
}
showHide() {
      tried this but not working
    //this.props.showHideSearch();
}
render() {
return (
    <div>// this props show not going to dashboard component
        <Dashboard show={this.props.show} showHide=  {this.showHide.bind(this)}/>
    </div>
)
}
}

export default Home;

【问题讨论】:

标签: reactjs


【解决方案1】:

如果我正确理解您的问题,您希望将您的 this.showHideSearch 函数从您的 App 组件传递给它在 this.props.children 中的组件 - 您的 Home 组件。

这很容易实现:

React.cloneElement(this.props.children, {showHideSearch: this.showHideSearch});

把它放在你有this.props.children的地方。

来源 - https://stackoverflow.com/a/35102287/6621973


编辑:要更新父级的状态,只需将设置状态的函数从父级传递给子级。如果你谷歌“react change parent state”有几个例子,例如:How to update parent's state in React?

【讨论】:

  • 那是我试图了解如何从主应用程序组件中使用的不同组件更新一个状态变量
  • 要更新父级的状态,只需将设置状态的函数从父级传递给子级即可。如果你谷歌“react change parent state”有几个例子,例如:stackoverflow.com/questions/35537229/…
猜你喜欢
  • 2015-08-22
  • 2020-11-06
  • 2015-12-02
  • 2016-02-04
  • 2019-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-19
相关资源
最近更新 更多