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

标签: htmlcssreactjsinline-styles

解决方案


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

推荐阅读