2017-03-16 57 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