【问题标题】:Why doesn't React automatically allow child components to call setState of the parent component?为什么 React 不自动允许子组件调用父组件的 setState?
【发布时间】:2018-08-06 05:30:15
【问题描述】:

我正在尝试将子组件设置为父组件,但它在 reactjs 中不起作用。

【问题讨论】:

  • 在 StackOverflow,我们也可以自己回答问题,分享知识。

标签: reactjs


【解决方案1】:

React 和 Flux 模式(帮助管理具有多个 React 组件的复杂应用程序)支持单向数据流。 单向数据流使应用程序易于推理和调试,因为:

  • 如果 React 组件有问题,您会递归地向上追踪到父组件,直到找到根本原因,因为数据流/setState 可能只来自上游

子 React 组件间接地设置父级的状态,但仅通过通知父级某些事件,例如鼠标单击。然后,父级本身决定鼠标单击是否应该触发其自身状态的 setState,该状态作为 props 传递给其子级。

class ParentComponent extends React.Component {
  onClick() {
    const _childValue = this.state.childValue; 
    this.setState({ childValue: _childValue + 1 });
  } 
  render() {
    return (<ChildComponent value={this.state.childVvalue} onClick={this.onClick.bind(this)} />)
  } 
} 
class ChildComponent extends React.Component {
  render() {
    return (
      <span> 
        <div>My value: {this.props.value} </div>
        <button onClick={this.props.onClick}>Increment</button> 
      </span> 
    ) 
  } 
} 

【讨论】:

  • 很高兴您发现我的回答很有帮助。
猜你喜欢
  • 2019-06-23
  • 2021-11-03
  • 1970-01-01
  • 1970-01-01
  • 2021-06-16
  • 1970-01-01
  • 2020-08-19
  • 2016-12-03
  • 2018-08-28
相关资源
最近更新 更多