我目前正在使用带有Gatsby和Material UI按钮的React。我希望最近按下的按钮具有某种状态。当前,当我运行代码时,我的所有4个按钮都被禁用,因为最近单击的那个按钮被禁用了。其他帖子说绑定是问题,但是我已经在这里做了。我该怎么做才能使这项工作按预期进行?
这是我在该类中编写的函数的代码:
constructor() {
super()
this.state = {
pressed: [true, false, false, false],
current: 0
}
}
getButtonState = location => {
return this.state.pressed[location]
}
changeButtonState(location){
const newState = this.state.pressed.slice() //copy the array
newState[location] = true //execute the manipulations
newState[this.state.current] = false
this.setState({
pressed: newState,
current: location
})
}
这是我的按钮渲染的代码:
render() {
return(
<div>
<Button variant="outlined" color="primary" disabled={ () => this.getButtonState(0) }
onClick={() => {this.changeButtonState(0)}} style={{ borderRadius: 25, margin: 4 }}>All</Button>
<Button variant="outlined" color="primary" disabled={ () => this.getButtonState(1) }
onClick={() => {this.changeButtonState(1)}} style={{ borderRadius: 25, margin: 4 }}>Mechanical</Button>
<Button variant="outlined" color="primary" disabled={ () => this.getButtonState(2)}
onClick={() => {this.changeButtonState(2)}} style={{ borderRadius: 25, margin: 4 }}>Software</Button>
<Button variant="outlined" color="primary" disabled={ () => this.getButtonState(3)}
onClick={() => {this.changeButtonState(3)}} style={{ borderRadius: 25, margin: 4 }}>Design</Button>
</div>
)
}
我该怎么办?
答案 0 :(得分:0)
您正在将disable设置为等于函数,但它接受布尔值。
此disable= {() => this.getButtonState(0)}
应该是disabled={this.getButtonState(0)}
您无需担心事件处理和绑定,因为您不需要传递函数