How can a React child component modify the state of its parent component?

In React, the state of a parent component can be passed down to a child component through props. If a child component needs to modify the state of the parent component, it can do so by calling a callback function passed down from the parent component.

Here is an example:

// 父组件
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>
    );
  }
}

In the example above, the state of the parent component, count, is passed to the child component, ChildComponent, through the updateCount callback function. The handleClick method in the child component can then be used to call the updateCount function in order to modify the parent component’s state.

bannerAds