2017-03-16 84 views
3

我想问一下,这里是场景。我有这个复选框,但我的问题是每当我勾选一个复选框时,所有4个复选框都被选中。而且为什么它复选框的值就是真或false.Here是我的复选框:多种形式的复选框

<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> 
+0

'ReduxForm'不支持复选框基。 [This](https://github.com/erikras/redux-form/issues/1037#issuecomment-243003954)可能会帮助您解决问题。 –

+0

嗨@JyothiBabuAraja你有一个例子如何实现它。我很新的反应:D。谢谢! –

+0

检查[this](https://github.com/erikras/redux-form/issues/635#issuecomment-239056316)和[示例](https://github.com/erikras/redux-form/issues/ 635#issuecomment-270785911) –

回答

6

对于我这样的人谁是新的终极版和反应可能会发现原来的代码中提到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} /> 
+0

非常感谢@ aftab-naveed! optionsList对象是什么样的?我试图实现它没有成功。 – Gaius

+0

让optionList = {id:1,name:'Optoin1',id:2,name:'Option 2'} –

+1

不错,但touch事件对我来说不起作用,它总是假的。第一个表格提交后,触摸了事件开始发射。 const {options,name,input,meta:{touched,error}} = this.props; const hasError =碰到&&错误; – TariqN