如何识别每个复选框



我正在构建todoList,当我选中该框时,该组件将消失。我试着用索引来识别每个复选框!因此,我使状态:checkedItem,它有一个";"假或真";状态。但是,它不会马上出现。

这是我的代码沙盒:https://codesandbox.io/s/old-voice-6xyovb?file=/src/App.js

import "./styles.css";
import React from "react";
const todos = [
{ id: 0, value: "Wash the dishes" },
{ id: 1, value: "have lunch" },
{ id: 2, value: "listen to music" },
{ id: 3, value: "running" },
{ id: 4, value: "work out" }
];
export default function App() {
const [items, setItems] = React.useState(todos);
const [checkedItems, setCheckedItems] = React.useState(
new Array(todos.length).fill(false)
);
const checkHandler = ({ target }, idx) => {
checkedItems[idx] = !checkedItems[idx];
setCheckedItems(checkedItems);
//I want to identify idx ..
};
return (
<div className="App">
{items.map((todo, idx) => (
<div key={idx}>
<span>{todo.value}</span>
<input
type="checkbox"
checked={checkedItems[idx]}
onChange={(e) => checkHandler(e, idx)}
></input>
</div>
))}
</div>
);
}

问题是,您调用setCheckedItems,但您给它的数组完全相同,因此这不被视为更改。

要解决这个问题,请确保给它一个新的数组:

setCheckedItems([...checkedItems]);

在这里,我用注释和修复程序更新了您的沙箱。

https://codesandbox.io/s/objective-ioana-b04r8f?file=/src/App.js

最新更新