gpt4 book ai didi

reactjs - React 和 Material 用户界面 : show and hide component onClick

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

我试图在单击 Button 时打开 Material UI Box 组件,并在再次单击 Button 时关闭 Box。我试图从谷歌搜索解决方案,但找不到任何简单的东西。我需要非常基本的解决方案。我没有尝试过的任何解决方案,因为我只是想知道该怎么做。

我假设我需要这些处理程序和其中的一些代码:

const [show, setShow] = useState(null);

const handleOpen = event => {
setOpen(event.currentTarget);
};

const handleClose = () => {
setOpen(null);
};

这是应该打开和关闭 Box 组件的 Button 组件。我需要两个功能。当我单击按钮时,它设置 Box !null 如果它是 null 和 null 如果它是 !null:

<Button 
className={classes.button}
onClick={handleOpen}
>
Click
</Button>
<Box className={classes.box}>
// Some content
</Box>

最佳答案

您需要使用状态来显示/隐藏您的组件。您可以像这样非常简单地处理(使用 Hooks)

import React, { useState } from 'react';

const Component = () => {
const [show, setShow] = useState(false);
return(
<>
<button onClick={() => setShow(prev => !prev)}>Click</button>
{show && <Box>This is your component</Box>}
</>
);
}

export default Component

关于reactjs - React 和 Material 用户界面 : show and hide component onClick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65788404/

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