gpt4 book ai didi

javascript - 删除使用 Material ui 和 Reactjs 创建的列表中的任何项目

转载 作者:行者123 更新时间:2023-12-01 15:53:55 25 4
gpt4 key购买 nike

一旦用户单击了该特定项目,我将尝试删除该列表项。

我创建了一个函数来进行样式更改

const completed = () =>{
return document.getElementById("demo").style.textDecoration='line-through'
};

列表生成如下,我使用了 Material ui 库
 <List dense={dense} >
{items.slice(0).reverse().map(x=> (
<ListItem key={x.id} button id="demo" onClick={completed} divider>
<ListItemText primary={listItems(x)}/>
<ListItemSecondaryAction />
</ListItem>

))}
</List>

从我编写的代码中,我只能遍历列表的第一项。每当我添加新项目时,我唯一能够删除的项目总是第一个项目。

我正在尝试找到一种方法将其应用于列表中的所有元素

最佳答案

使用 document.getElementById() 不是一个好习惯在 React 中,因为那时您正在直接访问 DOM。相反,您必须使用 ref .
来自官方React documentation

When to Use Refs There are a few good use cases for refs:

  • Managing focus, text selection, or media playback.
  • Triggering imperative animations.
  • Integrating with third-party DOM libraries.

但在你的情况下 我们可以通过使用 React state 轻松做到这一点.我假设您的 items存储在您的组件中 state在待办事项中,您需要存储它是否已完成( bool 值)。您可以像下面这样更新代码。
const completed = (id) => {
/* update the state by changing the completed value of the
clicked todo item */
this.setState({
items : this.state.items.map(item => {
if(item.id === id){
item.completed = true;
}
return item;
})
})

}

<List dense={dense}>
{this.state.items
.reverse()
.map(x => (
<ListItem
key={x.id}
button
// add a unique id
id={x.id}

// add a strike style depending on the completed property of the todo item
style={{ textDecoration : x.completed ? 'line-through' : 'none' }}

// call completed with the id
onClick={() => completed(x.id)}

divider
>
<ListItemText primary={listItems(x)} />
<ListItemSecondaryAction></ListItemSecondaryAction>
</ListItem>
))}
</List>

关于javascript - 删除使用 Material ui 和 Reactjs 创建的列表中的任何项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60824588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com