繁体   English   中英

使用按钮 onClick 移除 li 项目

[英]Removing li items with Button onClick

我正在尝试为每个 li 添加一个活动的“x”按钮,以便用户可以单击它以从列表中删除li 我已经添加了按钮,以便它与每个列表项一起出现,但我不知道我需要输入onClick以在单击后删除相应的 li 。 有什么建议么?

<div>
  <h5 className="col-lg-4 mt-4">Selected Files</h5>
  <ul className="nobull text-sm">
    {files.map((file) => (
      <li key={file.path}>
        <Button className="ml-3" close />
        {file.path} - {(file.size / 1024).toFixed(1)} KB
      </li>
    ))}
  </ul>
</div>

如果它对任何人有帮助,经过进一步的研究,我能够得到我的答案。 我创建了以下常量:

  const remove = file => {
    const newFiles = [...files];     // make a var for the new array
    newFiles.splice(file, 1);        // remove the file from the array
    setFiles(newFiles);              // update the state
  };

然后我更新了我的代码:

<div>
  <h5 className="col-lg-4 mt-4">Selected Files</h5>
  <ul className="nobull text-sm">
    {files.map((file, i) => (
      <li key={file.path} className="py-2">
        <Button className="ml-3" onClick={() => remove(i)} close />
        {file.path} - {(file.size / 1024).toFixed(1)} KB
      </li>
    ))}
  </ul>
</div>;

你可以尝试这样的事情:

const handleDelete = (index) => {
    let filesArr = [...files];

    filesArr.splice(index, 1);      // This will delete the element

    // Update the state with this modified array
    setFiles(filesArr);     // like this
}

<div>
  <h5 className="col-lg-4 mt-4">Selected Files</h5>
  <ul className="nobull text-sm">
    {files.map((file, fileIndex) => (           // fileIndex is added here to hold array element index
      <li key={file.path}>
        <Button className="ml-3" close />
        {file.path} - {(file.size / 1024).toFixed(1)} KB
        <button type="button" onClick={() => handleDelete(fileIndex)}
      </li>
    ))}
  </ul>
</div>;

您可以创建要删除的密钥数组。

function Files(){
   const [dis, setDis] = useState([]);

   const removeHandler = (key) => {
     setDis(dis.push(key))
   }
   return(
     <div>
       <h5 className="col-lg-4 mt-4">Selected Files</h5>
       <ul className="nobull text-sm">
         {files.map((file, key) => (
           !fruits.includes(key) && (
             <li key={file.path}>
               <Button className="ml-3" close onClick={()={removeHandler(key)}}/>
               {file.path} - {(file.size / 1024).toFixed(1)} KB
              </li>
            )
          ))}
        </ul>
     </div>;
   )
}
  you could use a function like this  const removeFile = id =>{ const updatedFiles = files.filter(file => file.id !== FileId)
setFiles(updatedFiles)

}

<Button className="ml-3" onClick={() => removeFile(id)} close />

暂无
暂无

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

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