我想在单击时更改组件的类。我使用state来创建一个具有name和done属性的新组件(创建时为false)。然后将其推入todos数组。现在的问题是,我如何找到哪个组件被单击并更改其"完成";属性到!done ?
function App() {
const [todos, setTodos] = useState([])
const [newTodo, setNewTodo] = useState({
name: "",
done: false
})
const handleInput = (event) => {
setNewTodo({name: event.target.value})
}
const handleDone = (event) => {
//WHAT TO DO HERE
}
const submitTodo = (event) => {
event.preventDefault();
setTodos([...todos, newTodo.name])
console.log(newTodo.name)
setNewTodo({name: ""})
}
return (
<div className="App">
<form onSubmit={submitTodo}>
<input onChange={handleInput} value={newTodo.name}/>
<button>Add Todo!</button>
</form>
<ul>
{todos.map(todo => (
<li className={/*Change the class based on the DONE property*/} onClick={handleDone}>{todo}</li>
))}
</ul>
</div>
);
}
export default App;
首先,您应该始终使您的待办事项包含name
和done
属性。有了这个,你只需将todo从点击的<li>
传递给你的点击处理程序,这样它就可以修改它的完成属性,并通过更新todos
状态来引起渲染。
function App() {
const [todos, setTodos] = useState([])
const [newTodo, setNewTodo] = useState({
name: "",
done: false
})
const handleInput = (event) => {
setNewTodo({name: event.target.value, done: false }); // this now adds done property
}
const handleDone = (todo) => {
todo.done = !todo.done;
setTodos([...todos]); // This sets new todos to cause a rerender with updated list
}
const submitTodo = (event) => {
event.preventDefault();
setTodos([...todos, newTodo]) // this now appends entire newTodo item not only it's name
setNewTodo({name: "", done: false}) // this now also sets default done
}
return (
<div className="App">
<form onSubmit={submitTodo}>
<input onChange={handleInput} value={newTodo.name}/>
<button>Add Todo!</button>
</form>
<ul>
{todos.map(todo => (
<li
className={todo.done ? 'classA' : 'classB'}
onClick={() => handleDone(todo)}
>
{todo.name} // this now displays todo.name not todo
</li>
))}
</ul>
</div>
);
}
export default App;
此外,您可以将todos和click处理程序提取到单独的组件中:
function ToDo({ item }) {
const [clicked, setClicked] = useState(item.done);
const handleClick = useCallback(() => {
item.done = !clicked
setClicked(!clicked);
}, [clicked]);
return <li
className={clicked ? 'classA' : 'classB'}
onClick={handleClick}
>
{item.name}
</li>;
}
然后用你的App组件渲染一个组件列表:
<ul>
{todos.map(todo => <ToDo item={todo} />
</ul>
更改newTodo状态
const [newTodo, setNewTodo] = useState('');
const [show,setShow] = useState(false);
const handleDone = (event) => setShow(!show)
.....
.....
.....
<li className={show ? 'classname when show is true': 'classname when show is false'} onClick={handleDone}>{todo}</li>