通过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,但这不起作用。

这里是https://i.stack.imgur.com/m5mfM.png

的样子

解决方法

除了使用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>
              );

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...