【问题标题】:How to change the Icon when clicking on it in react在反应中单击图标时如何更改图标
【发布时间】:2021-12-08 07:09:51
【问题描述】:

我有 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 ({btnClicked}) 行中检查 btnClicked 周围是否需要大括号吗?
  • 你能分享你所有代码的codeandbox吗!并使用更漂亮

标签: javascript reactjs react-hooks material-ui jsx


【解决方案1】:

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

if ({btnClicked}) {

你应该有

if (btnClicked) {

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

【讨论】:

    【解决方案2】:

    我注意到的第一件事是,您不应该在对象内部使用btnClicked

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-12
      • 2019-10-26
      • 1970-01-01
      • 2022-10-05
      • 2020-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多