toggleCheckbox = (type) => {
if(this.state.active_class === type)
{
this.setState({active_class:'health'});
}
else
{
this.setState({ active_class: type });
}
}
通过上述方法调用的此Button代码
以上代码仅适用于单选,如何进行多选?
然后我使用rails api存储选定的类别
<Button value="1" className={this.state.active_class === 'health' ? 'btn-primary': 'btn-default'} onClick={()=>{this.toggleCheckbox('health')}} > Health2 </Button>
<Button value="2" className={this.state.active_class ==='financial' ? 'btn-primary': 'btn-default'} onClick={()=>{this.toggleCheckbox('financial')}} > Financial </Button>
<Button value="3" className={this.state.active_class === 'career' ? 'btn-primary': 'btn-default'} onClick={()=>{this.toggleCheckbox('career')}} > Career </Button>
<Button value="4" className={this.state.active_class === 'people' ? 'btn-primary': 'btn-default'} onClick={()=>{this.toggleCheckbox('people')}} > People & Relationships </Button>
答案 0 :(得分:0)
要进行多重选择,您应该将所选按钮的名称(或)值保持在该状态。
this.state = {
activeButtons: []
}
toggleCheckbox = (type) => {
const { activeButtons } = this.state;
const newActiveBUttons = [...activeButtons];
if(activeButtons.includes?(type)){
newActiveBUttons = activeButtons.splice(activeButtons.indexOf(type), 1 );
} else {
newActiveBUttons.push(type);
}
}
render () {
const { activeButtons } = this.state;
return (
<Button value="1" className={(activeButtons.indexOf('health') > -1) ? 'btn-primary': 'btn-default'} onClick={()=>{this.toggleCheckbox('health')}} > Health2 </Button>
<Button value="2" className={(activeButtons.indexOf('financial') > -1) ? 'btn-primary': 'btn-default'} onClick={()=>{this.toggleCheckbox('financial')}} > Financial </Button>
<Button value="3" className={(activeButtons.indexOf( 'career') > -1) ? 'btn-primary': 'btn-default'} onClick={()=>{this.toggleCheckbox('career')}} > Career </Button>
<Button value="4" className={(activeButtons.indexOf( 'people') > -1) ? 'btn-primary': 'btn-default'} onClick={()=>{this.toggleCheckbox('people')}} > People & Relationships </Button>
)
}
这样,您可以进行多选。您可以使按钮值保持状态而不是名称。