如何在React js中做多个检查选项?

时间:2016-11-04 11:33:43

标签: javascript jquery reactjs lodash

基本上我有两种阵列。一个用于所有复选框值,另一个用于自定义值。所以,我的要求是我希望从默认的自定义数组值中选择值到复选框选项。如何用reactjs实现?

这是我的示例代码

var optionArray = ['item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7'], selectedValue = ['item1', 'item5'];

var Items = optionArray.map(function(el, i){
var isChecked = el == selectedValue;
                return <div key={i} className="radio-tick-row">
                    <input type="checkbox" className="radio-tick-input" id={"option"+i} value={el} name="selectOrganisationType" onChange={self.onChange.bind(self)} checked={isChecked} />
                    <label className="checkbox-tick-label term" htmlFor={"option"+i}><span>{el}</span></label>
                </div>;
        });

3 个答案:

答案 0 :(得分:1)

尝试if in数组条件:

var optionArray = ['item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7'], selectedValue = ['item1', 'item5'];

var Items = optionArray.map(function(el, i){
var isChecked = false;
                if(selectedValue.indexOf(el)) {
                   isChecked = true;
                 }
                return <div key={i} className="radio-tick-row">
                    <input type="checkbox" className="radio-tick-input" id={"option"+i} value={el} name="selectOrganisationType" onChange={self.onChange.bind(self)} defaultChecked={isChecked} />
                    <label className="checkbox-tick-label term" htmlFor={"option"+i}><span>{el}</span></label>
                </div>;
        });

答案 1 :(得分:0)

为了更好的观看以及ES 20的

const Items = optionArray.map((el, i) => {
  const isChecked = selectedValue.indexOf(el) > -1;
  return (
    <div key={i} className="radio-tick-row">
      <input type="checkbox" className="radio-tick-input" id={"option"+i}
         value={el} name="selectOrganisationType"
         onChange={self.onChange.bind(self)} checked={isChecked} />
      <label className="checkbox-tick-label term" htmlFor={"option"+i}>
        <span>{el}</span>
      </label>
    </div>
  );
}

答案 2 :(得分:0)

您可以使用Set

var optionArray = ['item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7'], selectedValue = ['item1', 'item5'];

var selectedValueSet = new Set(selectedValue);

var Items = optionArray.map(function(el, i){
    var isChecked = selectedValueSet.has(el);
    return (
        <div key={i} className="radio-tick-row">
            <input type="checkbox" className="radio-tick-input" id={"option"+i} value={el} name="selectOrganisationType" onChange={self.onChange.bind(self)} checked={isChecked} />
            <label className="checkbox-tick-label term" htmlFor={"option"+i}><span>{el}</span></label>
        </div>
    );
});