【问题标题】:How to use checkbox to complete tasks in a to do list?如何使用复选框完成待办事项列表中的任务?
【发布时间】:2020-06-09 00:37:44
【问题描述】:

我是 React 的新手,我一直在使用 State Hooks 制作一个简单的待办事项列表。我无法为 style={{textDecoration: Checkbox.checked ? "line-through" : "" }} 分配函数

function Checkbox(){
    const [checked, setChecked] = useState(false);
    return (
      <label>
        <input type="checkbox"
          checked={checked}
          onChange={() => setChecked(!checked)}
        />
      </label>
    );
  }

为了完成一些任务。任务应该是默认的“任务”,但一旦选中,我希望任务被划掉:“T̶a̶s̶k̶”。我会为你发布我的尝试:

import React, {useState} from 'react';

function TodoList({ todo, index, completeTodo, removeTodo}) {
    return (
      <div className="todo"> 
        <Checkbox />    
            <div style={{textDecoration: Checkbox.checked ? "" : "line-through" }} >
                {todo.text}
            </div>
        <div>
          <button class = "button" onClick={() => removeTodo(index)}>Delete Task</button>
        </div>
      </div>
    );
  }

  function Checkbox() {
    const [checked, setChecked] = useState(false);
  
    return (
      <label>
        <input type="checkbox"
          checked={checked}
          onChange={() => setChecked(!checked)}
        />
      </label>
    );
  }

export default TodoList;

【问题讨论】:

  • 奇怪的是 TodoList 只呈现单个 Todo 并且您正在从列表中删除项目但使用 index as key,查找 We don’t recommend using indexes for keys。您还有来自某个地方的completeTodo,但您认为在关于如何完成待办事项的问题中提及它的来源无关紧要。

标签: javascript reactjs checkbox react-hooks


【解决方案1】:

React 在单向数据绑定中工作,这意味着 Child 可以看到父状态,但父母 不能看到孩子的状态。

因此,为了实现您想要做的事情,您可以采取两条路径。

  1. (最简单)将文本移动到复选框功能组件内,这样做可以绑定两个元素(复选框和文本)并共享状态。

  2. (最难,在这种情况下不推荐)创建一个全局状态(使用上下文 api 或 Redux 或任何你想使用的)来将复选框的状态保存在全局状态中,然后在 TodoList 中读取它零件。

如果你想实现第一个路径,你可以这样做:

import React, {useState} from 'react';

function TodoList({ todoList }) {
    const onRemoveItem = () => {
      //remove item from todoList
    }

    return (
      <div className="todo"> 
        <Checkbox onRemoveItem={onRemoveItem} />
      </div>
    );
  }

  function Checkbox({ onRemoveItem }) {
    const [checked, setChecked] = useState(false);
  
    return (
    <>
      <label>
        <input type="checkbox"
          checked={checked}
          onChange={() => setChecked(!checked)}
        />
      </label>
      <div style={{textDecoration: checked ? "" : "line-through" }} >
        {todo.text}
      </div>
      <button class = "button" onClick={() => onRemoveItem()}>Delete Task</button>
    </>
    );
  }

export default TodoList;

【讨论】:

    猜你喜欢
    • 2016-04-09
    • 1970-01-01
    • 2020-05-05
    • 1970-01-01
    • 2020-11-05
    • 2022-07-26
    • 1970-01-01
    • 2023-01-21
    • 2020-03-30
    相关资源
    最近更新 更多