溫馨提示×

react子組件怎么修改父組件狀態(tài)

小億
163
2024-01-23 15:24:59
欄目: 編程語言

在 React 中,父組件的狀態(tài)是可以通過 props 傳遞給子組件的。當(dāng)子組件需要修改父組件的狀態(tài)時,可以通過在子組件中調(diào)用父組件傳遞過來的回調(diào)函數(shù)來實現(xiàn)。

以下是一個示例:

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

  // 用于更新父組件的狀態(tài)的回調(diào)函數(shù)
  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 = () => {
    // 調(diào)用父組件傳遞過來的回調(diào)函數(shù)來更新父組件的狀態(tài)
    this.props.updateCount(10);
  };

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

在上述示例中,父組件的狀態(tài) count 通過 updateCount 回調(diào)函數(shù)傳遞給子組件 ChildComponent,子組件中的 handleClick 方法可以調(diào)用 updateCount 函數(shù)來修改父組件的狀態(tài)。

0