【发布时间】:2021-11-02 10:00:28
【问题描述】:
const allTodos = [{id: 1, name: 'whatever user type'}, { }, { }, .... { }] // Defined as an array using setState in other file. Imported in this file as allTodos using props.
export const Todos = (props) => {
const [index, setIndex] = useState(0)
props.allTodos.map((prev) => {
return (
<div id="item_container">
<button type='button' className = `check_button ${prev.id === index ? 'checked' : 'not_checked'}`
onClick = {() => setIndex(prev.id)}>
<img src = {check} alt="" id = "check_img"></img>
</button>
<li id="li_item">{prev.name}</li>
</div>
)}
}
说明:在这里,我使用useState 设置了一个常量index,它将其值更改为单击的元素的ID,以更改该元素的className。
问题:现在,我成功地做到了,但每次我点击其他元素时,className 都会被添加到该元素中,但会从之前添加的元素中删除。现在我想以某种方式将className 保留给我单击的每个元素,直到我再次单击它们以更改它们的className。顺便说一句,我希望更改的样式是该按钮/元素的background。
【问题讨论】:
标签: reactjs react-functional-component