gpt4 book ai didi

reactjs - redux 形式的多个复选框

转载 作者:行者123 更新时间:2023-12-03 13:20:04 24 4
gpt4 key购买 nike

我想问一下,情况是这样的。我有多个复选框,但我的问题是每当我勾选一个复选框时,所有 4 个复选框都会被选中。还有为什么复选框的值只是 true 或 false。这是我的复选框:

<div className="checkbox">
<label><Field name="investor_stage" component="input" type="checkbox" value="Seed" /> Seed</label>
</div>
<div className="checkbox">
<label><Field name="investor_stage" component="input" type="checkbox" value="Early Stages" /> Early Stages</label>
</div>
<div className="checkbox">
<label><Field name="investor_stage" component="input" type="checkbox" value="Formative Stages" /> Formative Stages</label>
</div>
<div className="checkbox">
<label><Field name="investor_stage" component="input" type="checkbox" value=" Later Stages" /> Later Stages</label>
</div>

最佳答案

对于像我这样刚接触 redux 和 React 的人可能会发现提到的原始代码 here令人困惑。我修改并将其转换为 ES6 类。我还删除了 Bootstrap 、验证并使其易于调试。

这是修改后的代码

import React from 'react';

class CheckboxGroup extends React.Component {

checkboxGroup() {
let {label, required, options, input, meta} = this.props;

return options.map((option, index) => {
return (
<div className="checkbox" key={index}>
<label>
<input type="checkbox"
name={`${input.name}[${index}]`}
value={option.name}
checked={input.value.indexOf(option.name) !== -1}
onChange={(event) => {
const newValue = [...input.value];
if (event.target.checked) {
newValue.push(option.name);
} else {
newValue.splice(newValue.indexOf(option.name), 1);
}

return input.onChange(newValue);
}}/>
{option.name}
</label>
</div>)
});
}

render() {
return (
<div>
{this.checkboxGroup()}
</div>
)
}
}


export default CheckboxGroup;

用法:

let optionsList = [{id: 1, name: 'Optoin1'}, {id: 2, name: 'Option 2'}, {id: 3, name: 'Option 3'}]     
<Field name="roles" component={CheckboxGroup} options={optionsList} />

关于reactjs - redux 形式的多个复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42836060/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com