我在下面有这段代码,当我单击按钮时,它将呈现当前时间
但是当我再次点击更新新时间时,它会同时更新所有三个。我只想更新我点击的按钮
我猜问题是所有三个都使用相同的状态。
constructor(props) {
super(props);
this.state = {
button1: false,
button2: false,
button3: false,
};
}
onClickHandler = (type) => {
this.setState({[type]: true})
}
render() {
return (
<div>
{this.state.button1 && <div>{ this.state.curTime }</div>}
{this.state.button2 && <div>{ this.state.curTime }</div>}
{this.state.button3 && <div>{ this.state.curTime }</div>}
<div>
<Button
onClick={() => { this.getTimePress(); this.onClickHandler("button1") }}
>Button 1
</Button>
<Button
onClick={() => { this.getTimePress(); this.onClickHandler("button2") }}
>Button 2
</Button>
<Button
onClick={() => { this.getTimePress(); this.onClickHandler("button3") }}
>Button 3
</Button>
</div>
</div>
)
}
}
我正在考虑使用 map()
可能会解决问题,但我很难弄清楚如何修改每个按钮的布尔值。
this.state = {
buttonList: [
{ id: 'button1', title: "Button 1", pressed: false },
{ id: 'button2', title: "Button 2", pressed: false },
{ id: 'button3', title: "Button 3", pressed: false }
],
};
}
回答1
this.state = {
buttons: [
{ id: 'button1', title: "Button 1", pressed: false, timePress : null },
{ id: 'button2', title: "Button 2", pressed: false, timePress : null },
{ id: 'button3', title: "Button 3", pressed: false, timePress : null }
],
};
handlePressButton (button,index) {
this.state.buttons[index].pressed = true
this.state.buttons[index].timePress= Date.now() //or new Date()
this.setState({
buttons : [...this.state.buttons ]
})
}
render () {
return (
<>
this.state.buttons.map(button => <div> Pressed at : {button.timePress || "not yet"} </div> )
this.state.buttons.map((button , index) => <Button onClick={() =>this.handlePressButton(button,index)} > {button.title} </Button> )
</>
)
}