html - 通过 id onClick 在反应中更改样式仅工作一次
问题描述
我正在尝试为添加的每个任务更改每个列表项的样式,并且它可以工作......但只有一次。单击“完成”后,它应该划掉任务并运行样式。我假设其余任务不起作用,因为 id 应该只属于一个元素。我怎样才能解决这个问题?这是html
{tasks.map((x, key) => {
return (
<div className="task-list-item">
<ul>
<li className="li-title" id="title" key={key}>
{x.title}
</li>
<li className="li-desc" id="desc" key={key}>
{x.description}
</li>
</ul>
<div className="btn-container">
<button onClick={handleStyleComplete} className="task-btns">
Complete
</button>
<button className="task-btn-del">Delete</button>
</div>
</div>
);
这是 onClick 功能
const handleStyleComplete = (e) => {
document.getElementById("title").style.textDecoration = "line-through";
document.getElementById("title").style.color = "grey";
document.getElementById("desc").style.textDecoration = "line-through";
document.getElementById("desc").style.color = "grey";
e.target.style.backgroundColor = "transparent";
e.target.style.cursor = "auto";
e.target.style.border = "none";
e.target.style.color = "transparent";
};
我曾尝试使用 getElementByClassName.style,但这不起作用。
解决方案
除了使用 document.getElementById 之外,您还可以根据元素完成与否的任务状态将不同的样式应用于您的元素。
例如 :-
const [tasks, setCompleteTasks] = React.useState([]);
const handleStyleComplete = (id) => {
// tell your state here, that these task is complete.
setCompleteTasks([...tasks, id]);
};
{tasks.map((x, key) => {
// using this derived state you could apply styles here
const isCompleteTask = tasks.includes(x.id);
return (
<div className="task-list-item">
<ul>
<li className={isCompleteTask ? 'lineThroughStyles' : 'li-title'} id="title" key={key}>
{x.title}
</li>
<li className="li-desc" id="desc" key={key}>
{x.description}
</li>
</ul>
<div className="btn-container">
<button onClick={() => completeTasks(x.id)} className={isCompleteTask ? 'taskCompleteButtonStyles' : 'task-btns'}>
Complete
</button>
<button className="task-btn-del">Delete</button>
</div>
</div>
);
推荐阅读
- c++ - vscode 无法识别扩展名 .cpp.in
- android - 我可以在 Android 手机上运行 IOS 应用程序吗?
- flutter - 如何使用合并语义将 Cupertino 添加到 appbar
- c# - 继承 IdentityUser 和 IdentityDbContext 时脚手架不起作用 - Wep Api
- javascript - 使用 Discord.js 向频道发送消息时遇到问题
- holoviews - 为什么我的 HoloViews DynamicMap 不会响应参数值的更改而更新?
- javascript - 在加载时获取数据(NodeJS、JS、导出)
- python - 为什么使用类时 Tkinter bind() 会返回错误?
- git - 使用 Github Actions 推送到个人 VPS
- android - 短时间后音频播放在 Android 上停止,但在 IOS 上完全播放