Javascript 如何将状态作为道具传递,该道具将在稍后随单击事件更新(同时保持状态更新)
反应 我试着制作一个按钮,它将显示使用react state单击它的次数。但我想用很多组件来实现这一点。因此,我在父组件中使用setState编写了状态和更新函数,并希望将状态作为道具传递,但问题是,我只传递了一次状态,然后在状态更新后(当单击按钮时),道具不会随之更新。我看不出按钮被点击了多少次Javascript 如何将状态作为道具传递,该道具将在稍后随单击事件更新(同时保持状态更新),javascript,reactjs,Javascript,Reactjs,反应 我试着制作一个按钮,它将显示使用react state单击它的次数。但我想用很多组件来实现这一点。因此,我在父组件中使用setState编写了状态和更新函数,并希望将状态作为道具传递,但问题是,我只传递了一次状态,然后在状态更新后(当单击按钮时),道具不会随之更新。我看不出按钮被点击了多少次 class App extends Component { constructor(props) { super(props); this.state = { coun
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;
类应用程序扩展组件{
建造师(道具){
超级(道具);
此.state={
计数:2,
};
}
点击计数(){
此.setState((上一个)=>{
返回{count:prev.count+1};
})
}
render(){
返回(
);
}
}
导出默认应用程序;
您似乎没有将函数绑定到此上
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;
类应用程序扩展组件{
建造师(道具){
超级(道具);
此.state={
计数:2,
};
this.clickCount=this.clickCount.bind(this);//您可能错过了这个。。
}
点击计数(){
此.setState((上一个)=>{
返回{count:prev.count+1};
})
}
render(){
返回(
);
}
}
导出默认应用程序;
您试图将状态传递给哪个组件?提供更多信息???我正在尝试将状态传递给“MainContent”子组件实际上我正在子组件(MainContent)中执行eventlistener操作。我正在使用arrow函数来使用“clickCount”函数onClick={()=>props.handler}