javascript - 对状态中已检查字段的对象更新数组使用react

标签 javascript reactjs

const data = [
    {

      id: "1",
      checked: false,
    },
    {
      id: "2",
      checked: false,
    },
    {
      id: "3",
      checked: false,
    },
    {
      id: "4",
      checked: false,
    },
  ];
const [state, setState] = useState(data)

{state.map((item, index) => (
   <div key={index}>
     <input checked={item.checked} type="checkbox" />
     <span>{item}</span>
   </div>
))}

每当复选框勾选和取消勾选时,如何更新选中的内容?

一些示例,但我希望检查的项目是一个数组,例如 [{id: "1",检查: true,},{id: "2",检查: true,}];

enter image description here enter image description here

最佳答案

您可以将 onClick 添加到 input 并根据所选项目更新状态数据。

const handleChange = (id) => {
  const clonedData = [...state];
  setState(
    clonedData.map((d) => (d.id === id ? { ...d, checked: !d.checked } : d))
  );
};

//// Your remaining code 


<input
  checked={item.checked}
  type="checkbox"
  onClick={() => handleChange(item.id)}
/>;

附件是沙箱供引用。

Edit hopeful-bush-qpwsye

关于javascript - 对状态中已检查字段的对象更新数组使用react,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72108129/

相关文章:

javascript - 当你离开页面底部 100 像素时淡出 'scroll to top' 按钮

javascript - 为什么 JS Bin 告诉我潜在的无限循环?

javascript - flowtype - 函数参数只能是对象的属性值之一

reactjs - 如何访问 Cypress 中的 Component props

reactjs - 单元测试 : Actions must be plain objects. 使用自定义中间件进行异步操作

javascript - 将 div 放在链接内 - 区域在 div 外仍可点击

javascript - 在创建的函数中访问 axios 响应数据 - Vue2

javascript - 在辅助方法中 react i18next useTranslation Hook

reactjs - 使用 redux 中间件控制 react 路由器导航

php - 用于更快加载的前端 UI