如何在ReactJS中将多个复选框标记为已选中且其他复选框未选中?

时间:2018-03-26 09:33:21

标签: javascript reactjs

我有两个数组

masterList:

[
  { id: 0, description: "a" },
  { id: 1, description: "b" },
  { id: 2, description: "c" },
  { id: 3, description: "d" }
]

preferencesList:

[
  {id: 0, description: "a" },
  {id: 2, description: "c" }
]

我想要做的是,渲染四个复选框(或更多,取决于masterList的长度),并预先检查preferencesList中列出的复选框。

我试过但无法让它发挥作用。

这是我到目前为止所做的:

{
  this.state.masterList && this.state.masterList.length ? (
    this.state.masterList.map((item, index) => (
      <div key={`item_${index}`} className="form-group">
        <div className="checkbox">
          <label>
            {this.state.preferencesList && this.state.preferencesList.length
              ? this.state.preferencesList.map(
                  insurerFeature =>
                    insurerFeature.id == item.id ? (
                      <input
                        type="checkbox"
                        onChange={this.changeFeaturePreferences}
                        value={item.id}
                        defaultChecked
                      />
                    ) : (
                      <input
                        type="checkbox"
                        onChange={this.changeFeaturePreferences}
                        value={item.id}
                      />
                    )
                )
              : "failed to get insurers items"}
            {item.description}
          </label>
        </div>
      </div>
    ))
  ) : (
    <p>There are no items available.</p>
  );
}

changeFeaturePreferences方法:

changeFeaturePreferences = event => {
  let { id } = this.state.resource;
  let featureId = event.target.value;
  let checkbox = event.target;

  // Reset state
  this.setState({ success: null });

  // Add Feature
  if (checkbox.checked) {
    let payload = [featureId];
    return MyService.setMyFeatures(id, payload).then(
      response => this.setState({ success: true }),
      error => this.setState({ success: false })
    );
  }
  // Remove Feature
  if (!checkbox.checked) {
    return MyService.deleteMyFeatures(id, featureId).then(
      response => this.setState({ success: true }),
      error => this.setState({ success: false })
    );
  }
  // Return with error
  return this.setState({ success: false });
};

2 个答案:

答案 0 :(得分:2)

我首先将preferencesList转换为Object,这样您就可以在JSX中的初始映射和更简单的逻辑之后进行常量查找。您可以执行以下操作:

const isChecked = {};
preferencesList.forEach(preference => { isChecked[preference.id] = true; });

{
  this.state.masterList && this.state.masterList.length ? (
    this.state.masterList.map((item, index) => (
      <div key={`item_${index}`} className="form-group">
        <div className="checkbox">
          <label>
            <input
              type="checkbox"
              onChange={this.changeFeaturePreferences}
              value={item.id}
              defaultChecked={isChecked[item.id]}
            />
            {item.description}
          </label>
        </div>
      </div>
    ))
  ) : (
    <p>There are no items available.</p>
  );
}

答案 1 :(得分:2)

您可以使用Array.prototype.some()来确定对象是否存在于preferencesList

  

some()方法测试数组中是否至少有一个元素   通过由提供的函数实现的测试。

示例

{
  this.state.masterList && this.state.masterList.length ? (
    this.state.masterList.map((item, index) => {
      const checked = preferencesList.some((checkedItem) => checkedItem.id === item.id);
      return (
      <div key={`item_${index}`} className="form-group">
        <div className="checkbox">
          <label>
            <input
              type="checkbox"
              onChange={this.changeFeaturePreferences}
              value={item.id}
              checked={checked}
            />
            {item.description}
          </label>
        </div>
      </div>
    )})
  ) : (
    <p>There are no items available.</p>
  );
}