ReactJs/Semantic UI 在循环中选中复选框

huangapple go评论72阅读模式
英文:

ReactJs/Semantic UI check checkbox in loop

问题

I render some checkbox via json data with map:

Data.FacData.map((v, i) => (
  <div key={i} className="CheckBox">
    <input
      type="checkbox"
      name="Facilities"
      value={v.id}
      onChange={this.getFacilities}
      id={"Facilities-" + v.id}
    />
    <label htmlFor={"Facilities-" + v.id}>{v.name}</label>
  </div>
))

It work fine and you can select any checkbox and get it as array on console log (I handle and save it to the database somehow), but now I want to get what user selected before, from the database (API). I got this data (object):

facilities: "1,3"

This means the user selected checkboxes 1 and 3. I want to make checkboxes checked. What I tried is using the defaultChecked property, but it selects all checkboxes, not only 1 and 3. Any solution?

英文:

I render some checkbox via json data with map:

Data.FacData.map((v, i) =&gt; (
  &lt;div key={i} className=&quot;CheckBox&quot;&gt;
    &lt;input
      type=&quot;checkbox&quot;
      name=&quot;Facilities&quot;
      value={v.id}
      onChange={this.getFacilities}
      id={&quot;Facilities-&quot;+v.id}
      /&gt;
    &lt;label htmlFor={&quot;Facilities-&quot; + v.id}&gt;{v.name}&lt;/label&gt;
  &lt;/div&gt;
))

JSFiddle

It work fine and you can select any chekcbox and get it as array on console log (I handle and save it to database somehow) , but now I want to get what user selected before, from database (api), I got this data (object)

facilities: &quot;1,3&quot;

This mean user select checkbox 1 and 3, I want to make checkbox checked, what I tried is use defaultChecked property, but it select all checkbox not only 1,3, any solution?

JSFiddle

答案1

得分: 2

更新你的代码如下,或者参考 https://jsfiddle.net/L7y2m8zr/17/。你需要使用 split 方法将值字符串转换为数组。

componentDidMount() {
  /* 从 API 获取数据 */
  const data = "1,3";
  const newValues = data.split(",").map(n => parseInt(n));
  this.setState({
    facilitiesValue: newValues
  });
}

另外,你可以根据数组是否包含给定的 id 来设置 defaultCheckedchecked 的值,而不仅仅传递数组或字符串(因为这是代码,不是魔法 :))。

return (
  <div>
    {
      Data.FacData.map((v, i) => (
        <div key={i} className="CheckBox">
          <input
            type="checkbox"
            name="Facilities"
            value={v.id}
            onChange={this.getFacilities}
            id={"Facilities-" + v.id}
            checked={this.state.facilitiesValue.includes(parseInt(v.id))}
          />
          <label htmlFor={"Facilities-" + v.id}>{v.name}</label>
        </div>
      ))
    }
  </div>
)

此外,更新 onchange 处理程序以更新状态。

getFacilities = (e) => {
  const checked = this.state.facilitiesValue;
  let index;

  if (e.target.checked) {
    checked.push(parseInt(e.target.value))
  } else {
    index = checked.indexOf(parseInt(e.target.value))
    checked.splice(index, 1)
  }
  console.log(checked)
  this.setState({
    facilitiesValue: [...checked]
  })
};
英文:

update your code like this
or refer https://jsfiddle.net/L7y2m8zr/17/
you need to convert the value string to array using split

componentDidMount() {
  /*get data from api*/
  const data = &quot;1,3&quot;
  const newValues = data.split(&quot;,&quot;).map(n =&gt; parseInt(n))
  this.setState({
    facilitiesValue: newValues
  });
}

also you can set the defaultChecked or checked value based on whether the array includes the given id, instead of just passing the array or string( since this is code and not magic ReactJs/Semantic UI 在循环中选中复选框 )

return (
    &lt;div&gt;
    {
        Data.FacData.map((v, i) =&gt; (
        &lt;div key={i} className=&quot;CheckBox&quot;&gt;
             &lt;input
             type=&quot;checkbox&quot;
             name=&quot;Facilities&quot;
             value={v.id}
             onChange={this.getFacilities}
             id={&quot;Facilities-&quot;+v.id}
             checked = {this.state.facilitiesValue.includes(parseInt(v.id))} 
            /&gt;
             &lt;label htmlFor={&quot;Facilities-&quot; + v.id}&gt;{v.name}&lt;/label&gt;
        &lt;/div&gt;
        ))
     }
    &lt;/div&gt;
)

also update the onchange handler, to update the state

getFacilities = (e) =&gt; {
  const checked = this.state.facilitiesValue;
  let index;

  if (e.target.checked) {
    checked.push(parseInt(e.target.value))
  } else {
    index = checked.indexOf(parseInt(e.target.value))
    checked.splice(index, 1)
  }
  console.log(checked)
  this.setState({
    facilitiesValue: [...checked]
  })
};

huangapple
  • 本文由 发表于 2020年1月3日 17:39:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/59576165.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定