javascript - 如何在页面呈现时停止 onClick 呈现?
问题描述
我目前正在将 React 与 Gatsby 和 Material UI 按钮一起使用。我希望最近按下的按钮具有某种状态。目前,当我运行我的代码时,我的所有 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>
)
}
我能做些什么??
解决方案
您将禁用设置为等于一个函数,但它接受一个布尔值。这disable= {() => this.getButtonState(0)}
应该是disabled={this.getButtonState(0)}
您无需担心事件处理和绑定 this,因为您不需要传递函数
推荐阅读
- android - BBWebview 和 GDWebview 有什么区别?
- python - 在python中移动文件时的反斜杠与正斜杠
- matlab - 如何在 Octave 中渲染结构化网格
- powershell - 使用 PowerShell 自动化 SSRS,包括带参数的文件名
- r - 有没有办法每次使用新的输入数据集多次运行 RMarkdown 并分别保存每个针织 Word 文档?
- reactjs - 将 Chakra-UI 添加到现有的 Create-React-App 会搞砸很多事情
- laravel - laravel withsum 附加 where 子句
- symfony - 如何仅为本地环境启用 Symfony Profiler 工具栏?
- android - 如何在中文 android 盒子的 Google Playstore 控制台中查找设备名称,以便将它们从支持的设备中排除?
- python - 将 ARIMAX 预测分解为 exog 变量和 ARIMA 参数的贡献