我有一些数组中的数据。正如您在下面的示例中看到的,我是通过使用 map 来获取它的。另外,我将其传递给按钮。现在,如果我选择一个按钮,它将被选中。但是,如果我选择下一个按钮,上一个按钮将被取消选择,当前按钮将被选中。我不希望它发生。我想选择多个按钮,如果它们都被点击的话。
提前致谢。
下面是解决方案
import React, { Component } from 'react';
const BUTTONS = [
{id:0, title:'button1'},
{id:1, title:'button2'},
{id:2, title:'button3'}
]
class Map extends Component {
constructor(props){
super(props);
this.state = {
values: []
}
}
handleButton = button => {
let tmp = this.state.values;
if (this.state.values.includes(button)) {
this.setState({
values: this.state.values.filter(el => el !== button)
})
} else {
tmp.push(button);
this.setState({
values: tmp
})
}
}
render () {
return (
<div>
{BUTTONS.map(bt=>(
<button
key={bt.id}
onClick={()=>this.handleButton(bt.id)}
className={this.state.values.includes(bt.id) ? "buttonPressed" : "button"}>
{bt.title}
</button>
))}
</div>
);
}
}
export default Map;
最佳答案
选择多个
按钮
您最好将
状态
用作数组
。
this.state = {
values: []
}
并且您可以推送
项。
let tmp = this.state.values;
tmp.push(button);
this.setState({
values: tmp
});
在 render()
你必须检查 state.values
有 bt.id
className={this.state.values.includes(bt.id) ? "buttonPressed" : "button"
切换多个
按钮
您可以在
handleButton()
中检查所选按钮是否已被选中
handleButton = button => {
if (this.state.values.includes(button)) {
this.setState({
values: this.state.values.filter(el => el !== button)
})
}
const BUTTONS = [
{ id: 0, title: 'button1' },
{ id: 1, title: 'button2' },
{ id: 2, title: 'button3' }
]
class Map extends React.Component {
constructor(props) {
super(props);
this.state = {
values: []
}
}
handleButton = button => {
let tmp = this.state.values;
if (this.state.values.includes(button)) {
this.setState({
values: this.state.values.filter(el => el !== button)
})
} else {
tmp.push(button);
this.setState({
values: tmp
})
}
}
render() {
return (
<div>
{BUTTONS.map(bt => (
<button
key={bt.id}
onClick={() => this.handleButton(bt.id)}
className={this.state.values.includes(bt.id) ? "buttonPressed" : "button"}>
{bt.title}
</button>
))}
</div>
);
}
}
export default Map;
关于javascript - 在 Reactjs 中选择多个选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55453192/