如何在react中点击图标时改变它



我有2个mui图标,我想每次点击切换。我为它们创建了一个组件,其中一个道具(称为btnClicked)决定了状态,组件在单击时呈现,但图标按钮不改变;代码是:

import React,{useState} from 'react';
import {IconButton } from '@material-ui/core';
import AddIcon from '@mui/icons-material/Add';
import UndoIcon from '@mui/icons-material/Undo';
import CreateOutlinedIcon from '@mui/icons-material/CreateOutlined'
import BorderColorIcon from '@mui/icons-material/BorderColor'
const AddButton = ({onBtnClick,btnClicked,btnText,btnColor}) => {
const create = () => {
return (
<div>
<IconButton
aria-label="add an alarm"
onClick={onBtnClick}
>
<BorderColorIcon
color="secondary"
style={{cursor:'pointer'}}
/>
</IconButton>
</div>
)
}
const undo = () => {
return (
<div>
<IconButton
aria-label="add an alarm"
onClick={onBtnClick}
>
<UndoIcon
color="secondary"
style={{cursor:'pointer'}}
/>
</IconButton>
</div>
)
}
console.log(btnColor)
if ({btnClicked}) {
return(
<div>
{
create()
}
</div>
)
}
else
{
return(
<div>
{
undo()
}
</div>
)
}
}
export default AddButton

请帮帮我:)

if语句中包含不必要的括号。而不是

if ({btnClicked}) {

你应该有

if (btnClicked) {

如果你的组件仍然没有更新,那么你没有从父组件更新道具。您需要确保onBtnClick触发对props

的更新。

我注意到的第一件事是你不应该在对象中使用btnClicked

if (btnClicked) {
return(
<div>
{
create()
}
</div>
)
}

最新更新