首页 > 解决方案 > 在 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>

)}
}

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

标签: reactjsreact-functional-component

解决方案


条件类- 根据条件选择特定类(在这种情况下 - 如果 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。


推荐阅读