首页 > 解决方案 > 如何将状态作为道具传递,稍后将通过点击事件更新(同时保持状态更新)

问题描述

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;

标签: javascriptreactjs

解决方案


您似乎错过了将函数绑定到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;

推荐阅读