react中的元素操作



所以我有一系列代码,其中Header.jsx文件中的一个按钮,如果单击,它将显示Notification.jsx文件的内容。这里的问题是,我不知道如何在index.js中显示Notification.jsx的内容。我尝试使用条件语句,单击按钮后是否可以隐藏h1元素?

Header.jsx

import React from "react";
import { Button } from "@mui/material";
import { IconButton } from "@mui/material";
import NotificationsIcon from "@mui/icons-material/Notifications";
import SearchIcon from "@mui/icons-material/Search";
import Menu from "@mui/material/Menu";
import MenuItem from "@mui/material/MenuItem";
import FullNotifList from "./FullNotifList"
export default function Header() {
const [anchorEl, setAnchorEl] = React.useState(null);
const open = Boolean(anchorEl);
const handleClick = (event) => {
setAnchorEl(event.currentTarget);
};
const handleClose = () => {
setAnchorEl(null);
};
return (
<div>
<Button
id="basic-button"
aria-controls={open ? "basic-menu" : undefined}
aria-haspopup="true"
aria-expanded={open ? "true" : undefined}
onClick={handleClick}
>
<IconButton>
<NotificationsIcon />
</IconButton>
</Button>
<Menu
id="basic-menu"
anchorEl={anchorEl}
open={open}
onClose={handleClose}
MenuListProps={{
"aria-labelledby": "basic-button",
}}
>
{/* Button needs to be clicked in order to display Notification.jsx */}
<Button variant="contained">Notification Center</Button> 
<MenuItem onClick={handleClose}>Profile</MenuItem>
<MenuItem onClick={handleClose}>My account</MenuItem>
<MenuItem onClick={handleClose}>Logout</MenuItem>
</Menu>
<IconButton>
<SearchIcon />
</IconButton>
</div>
);
}

Notification.jsx

import React from "react";
export default function Notification(){
return(
<div>
<ul>
<li> Hello </li>
<li> Hello </li>
<li> Hello </li>
<li> Hello </li>
</ul>
</div>
)
}

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import reportWebVitals from './reportWebVitals';
import Header from './Header'
import './index.css'
import Footer from './Footer';
import Notification from './Notification';
export default function Page(props) {
const [isClicked, setIsClicked] = React.useState(false)
function showHide(e) {
setIsClicked(true)
};
return(
<div className='main'>
<Header onClick={showHide}/>
{isClicked && <Notification />}
<h1> Sample body </h1>
<Footer />
</div>
)
}
ReactDOM.render(
<Page />,
document.getElementById('root')
);

以下是沙箱链接:https://codesandbox.io/s/friendly-darkness-9u5s22?file=/src/index.js

您只需要创建一个状态属性来处理元素是否可见(例如:showNotification(默认为false:

const [showNotification, setShowNotification] = React.useState(false);

然后使用按钮点击事件将其设置为true

<Button variant="contained" onClick={()=>{setShowNotification(true)}}>Notification Center</Button>

然后,通过在JSX中使用&&操作符来实现条件呈现,类似于:

{showNotification && <Notification />}

问题是Header组件没有prop-onClick,所以没有执行任何操作。

最新更新