reactjs - 在 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 但样式已添加到每个项目中。所以,它没有成功。
解决方案
条件类- 根据条件选择特定类(在这种情况下 - 如果 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。
推荐阅读
- php - 一个在我的 PHP 代码中不起作用但可与 SQL 客户端一起使用的存储过程
- vba - 使用 InputBox 更改外部参考
- xml - VTD-XML:只有结束标签检查不起作用
- node.js - 处理 env 文件的最佳方法是什么?
- python - 我无法在 http 上使用 oauth2 验证 CKAN 2.7.2
- .net - ThreadPool C# 的更好替代品?
- c++ - 尝试为 Intel 编译器切换 MSVC 并出现 LNK1243 错误
- jquery - jquery closest doesn't work
- visual-studio-code - VSCode pipenv 已激活问题
- asp.net-mvc - C# MVC - RazorEngine 电子邮件模板创建带有 URL 链接的按钮