簡體   English   中英

如何將狀態作為道具傳遞,該道具將在稍后通過單擊事件更新(並同時保持狀態更新)

[英]how to pass a state as props which will update later with click event (and also keep the state updated at the same time)

React我試圖制作一個按鈕,該按鈕將顯示使用React狀態點擊了多少次。 但我想用很多組件來做到這一點。 所以我在父組件中用 setState 編寫了我的狀態和更新函數,並希望將狀態作為道具傳遞,但問題是我傳遞了一次狀態,然后在狀態更新后(單擊按鈕時)道具不會更新。 我看不到按鈕被點擊了多少次。

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 2,
    };
  }
  clickCount() {
    this.setState((prev) => {
      return { count: prev.count + 1 };
    })
  }

  render() {
    return (
      <div>
        <MainContent 
        handler={this.clickCount}  totalCount={this.state.count}/>
      </div>
    );
  }
}

export default App;

您似乎錯過了將函數綁定到this

class App extends Component {
     constructor(props) {
          super(props);
          this.state = {
               count: 2,
          };
          this.clickCount = this.clickCount.bind(this); // you may have missed this..
     }
clickCount() {
this.setState((prev) => {
  return { count: prev.count + 1 };
})
}
render() {
     return (
          <div>
               <MainContent handler={this.clickCount}  totalCount={this.state.count}/>
          </div>
      );
}
}
export default App;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM