将特定样式添加到 React 中映射数组的特定项

Adding a specific styling to a specific item of a mapped array in React

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) => {

props.allTodos.map((prev) => {
return (

<div id="item_container">

<button type='button' className = 'check_button'
onClick = {() => setActiveTodos(prev.id)}>

<img src = {check} alt="" id = "check_img"></img>

</button>

<li id="li_item">{prev.name}</li>
</div>

)}
}

现在,问题是我想为点击的元素(按钮)添加一些特定的样式。我想添加的样式只是更改单击的 Button 的背景。 我尝试使用条件来设置 className 但样式已添加到每个项目。所以,没有成功。

conditional class - 根据条件选择特定的 class(在这种情况下 - 如果 activeTodos 状态 == 当前索引)

props.allTodos.map((prev, i) => {
            <button type = 'button' key ={i}
            className= {`${prev.id == activeTodos ? "active" : "inactive"}
            onClick={e => setActiveTodos(prev.id)}} 
            </button>
        }

有一些组合(例如每次只能选择1个或4个)

如果您不想选择 4 个项目(例如从 6 个中选择)- 则可以将活动 ID 保存在数组中。