如何解决使用 Button onClick 删除 li 项目
我正在尝试为每个 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)
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。