简体   繁体   English

有条件地在地图内渲染输入

[英]Conditional rendering an input inside a map

I have a list of task which inside have another task(subTask).我有一个任务列表,里面有另一个任务(子任务)。 I use a map to list all the tasks and have a button to add more subtasks to that task.我使用地图列出所有任务,并有一个按钮可以向该任务添加更多子任务。 The input button is supposed to be invisible unless the button is pressed.除非按下按钮,否则输入按钮应该是不可见的。 The problem is that I used the useState hook to conditional render the input but whenever I click in any of the button, the inputs of all tasks open and is supposed to only open the input from that certain index.问题是我使用 useState 挂钩有条件地呈现输入,但是每当我单击任何按钮时,所有任务的输入都会打开,并且应该只打开来自该特定索引的输入。

const Task = () => {
  const [openTask, setOpenTask] = useState(false);

  return task.map((item, index) => {
    return (
      <div>
        <button onClick={() => setOpenTask(!openTask)}>Add</button>
        {item.name}
        {openTask && <input placeholder="Add more tasks..."/>}
        {item.subTask.map((item, index) => {
          return (
            <>
              <span>{item.name}</span>
            </>
          );
        })}
      </div>
    );
  });
};

That's because you are setting openTask to true for all the items.那是因为您将所有项目的 openTask 设置为 true。 You can create object and store the specific id to true.您可以创建对象并将特定 id 存储为 true。 for eg.例如。

const [openTask, setOpenTask] = useState({});

and then on button onClick you can set the specific id to open然后在按钮 onClick 上可以设置要打开的具体 id

setOpenTask({...openTask,[`${item.name}-${index}`]:true});

and then check against specific id然后检查特定的 id

{openTask[`${item.name}-${index}`] && <input placeholder="Add more tasks..."/>}

Try using array尝试使用数组

const Task = () => {
    const [openTask, setOpenTask] = useState([]);
  
    const openTaskHandler = (id) => {
        setOpenTask([id])
    }
    return task.map((item, index) => {
      return (
        <div>
          <button onClick={() => openTaskHandler(item.id)}>Add</button>
          {item.name}
          {openTask.includes(item.id) && <input placeholder="Add more tasks..."/>}
          {item.subTask.map((item, index) => {
            return (
              <>
                    <span>{item.name}</span>
              </>
            );
          })}
        </div>
      );
    });
  };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM