在反应中单击图标时如何更改图标

How to change the Icon when clicking on it in 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

请帮助我:)

我注意到的第一件事是您不需要 btnClicked 对象内部。

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

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

if ({btnClicked}) {

你应该

if (btnClicked) {

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

的更新