温馨提示×

react子组件怎么修改父组件状态

小亿
114
2024-01-23 15:24:59
栏目: 编程语言

在 React 中,父组件的状态是可以通过 props 传递给子组件的。当子组件需要修改父组件的状态时,可以通过在子组件中调用父组件传递过来的回调函数来实现。

以下是一个示例:

// 父组件
class ParentComponent extends React.Component {
  state = {
    count: 0
  };

  // 用于更新父组件的状态的回调函数
  updateCount = (newCount) => {
    this.setState({ count: newCount });
  };

  render() {
    return (
      <div>
        <ChildComponent updateCount={this.updateCount} />
        <p>Count: {this.state.count}</p>
      </div>
    );
  }
}

// 子组件
class ChildComponent extends React.Component {
  handleClick = () => {
    // 调用父组件传递过来的回调函数来更新父组件的状态
    this.props.updateCount(10);
  };

  render() {
    return (
      <button onClick={this.handleClick}>Update Count</button>
    );
  }
}

在上述示例中,父组件的状态 count 通过 updateCount 回调函数传递给子组件 ChildComponent,子组件中的 handleClick 方法可以调用 updateCount 函数来修改父组件的状态。

0