gpt4 book ai didi

reactjs - 单击时如何切换 Material UI 图标

转载 作者:行者123 更新时间:2023-12-05 02:59:09 25 4
gpt4 key购买 nike

在列表中,每个列表项都有一个“AddIcon”。单击时,我想根据它的“id”将该图标切换为“BlockIcon”

import React from 'react'
import {List, ListItem} from '@material-ui/core'
import AddCircleIcon from '@material-ui/icons/AddCircleOutline'
import BlockIcon from '@material-ui/icons/BlockOutlined'

const StackOverflow = () => {
const handleIconClick = (id) => {
// change <AddCircleIcon /> to <BlockIcon /> at "id"
}
return (
<List component="nav">
<ListItem>
<ListItem button onClick={handleIconClick(101)}>
<AddCircleIcon />
</ListItem>
</ListItem>
</List>
)
}

export default StackOverflow

单击图标时,我希望 AddIcon 更改为 BlockIcon。

最佳答案

你应该创建一个状态变量来保存clickec或没有点击你的状态,你可以用它来交换图标

import React from 'react'
import {List, ListItem} from '@material-ui/core'
import AddCircleIcon from '@material-ui/icons/AddCircleOutline'
import BlockIcon from '@material-ui/icons/BlockOutlined'

const StackOverflow = () => {
const [clicked, setClicked] = useState(false)
const handleIconClick = (id) => {
setClicked(true)
// change <AddCircleIcon /> to <BlockIcon /> at "id"
}
return (
<List component="nav">
<ListItem>
<ListItem button onClick={handleIconClick(101)}>
{clicked ? <BlockIcon /> : <AddCircleIcon /> }
</ListItem>
</ListItem>
</List>
)
}

export default StackOverflow

我还注意到,由于您使用的是列表,因此您可能希望单击多个项目,如果是这种情况,那么您应该采用以下形式

const StackOverflow = () => {
const [clicks, setClicks] = useState([])
//add the id to the array of clicked items if it doesn't exist but if it does exist remove it. this makes sure that double clicking on an item brings it back to normal
const handleIconClick = (id) => {
let result = clicks.includes(id)? clicks.filter(click => click != id): [...clicks, id]
setClicks(result)
// change <AddCircleIcon /> to <BlockIcon /> at "id"
}
return (
<List component="nav">
<ListItem>
<ListItem button onClick={handleIconClick(101)}>
{clicks.includes(101) ? <BlockIcon /> : <AddCircleIcon /> }
</ListItem>
</ListItem>
</List>
)
}

export default StackOverflow

在 return 语句中,请注意,如果您在显示之前循环遍历项目,那么您将必须发送,但 clicks.include(id) 和 handleIconClick(id) 中的 id 现在将使用 id 而不是硬编码的数字

关于reactjs - 单击时如何切换 Material UI 图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58257228/

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