Geo*_*lva 4 javascript strikethrough reactjs material-ui
一旦用户单击该特定项目,我就尝试删除该列表项目。
我创建了一个函数来进行样式更改
const completed = () =>{
return document.getElementById("demo").style.textDecoration='line-through'
};
Run Code Online (Sandbox Code Playgroud)
列表生成如下,我使用了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>
Run Code Online (Sandbox Code Playgroud)
从我编写的代码中,我只能删除列表的第一项。每当我添加新项目时,我唯一能够删除的项目总是第一个项目。
我正在尝试找到一种方法将其应用于列表中的所有元素
在 React 中使用这不是一个好的做法,document.getElementById()因为这样你就直接访问 DOM。相反,您必须使用ref.
何时使用引用 引用有一些很好的用例:
- 管理焦点、文本选择或媒体播放。
- 触发命令式动画。
- 与第三方 DOM 库集成。
但就您而言,我们可以使用 React 轻松做到这一点state。我假设您items存储在组件state和待办事项中,您需要存储它是否完成(布尔值)。您可以像下面这样更新代码。
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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6327 次 |
| 最近记录: |