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

标签 javascript reactjs

我有两个数组

主列表:

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

偏好列表:

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

我想要做的是,渲染四个复选框(或更多,具体取决于 masterList 的长度)并仅预检查首选项列表中列出的那些复选框。

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

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

{
  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 });
};

最佳答案

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

The some() method tests whether at least one element in the array passes the test implemented by the provided function.

示例

{
  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>
  );
}

关于javascript - 如何在 ReactJS 中将多个复选框标记为已选中而其他复选框未选中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49488188/

相关文章:

javascript - 现代浏览器是并行加载脚本还是顺序加载脚本?

javascript - CORS 在 jquery 中工作正常但在 angularjs 中不工作

javascript - 每个 React 组件都应该有自己的样式表吗?

reactjs - 与 'wss:localhost:60001/w' 的 Websocket 连接失败:连接建立时出错:net::ERR_SSL_PROTOCOL_ERROR

javascript - Highcharts 删除第一个条之前和最后一个之后的空格

javascript - 如何使用 CSS 和 Javascript 制作滚动行的 Divs?

javascript - jquery 使用 codeigniter 框架发布数据在 PHP 中不可见

javascript - 在链接在react-router-dom上工作之前如何更改状态

java - 我可以使用 ScrollView 代替 Container View 吗?

node.js - Next.js 找不到模块 loader.js