如何使用React Material UI的styled自定义AppBar?解决重复声明报错
错误原因
- 从
@mui/material/AppBar导入的原始组件变量名为MuiAppBar,后续调用styled生成自定义组件时,新变量重复使用了MuiAppBar作为命名,同一作用域下重复声明变量触发报错。 - 代码还存在其他隐藏问题:未导入
IconButton组件、未声明drawerWidth常量、未在组件内定义open状态和handleDrawerOpen方法。
解决方案
将自定义styled组件的命名与导入的原始MUI组件名区分即可,修正后完整代码如下:
import * as React from 'react'; import { styled, useTheme } from '@mui/material/styles'; import MuiAppBar from '@mui/material/AppBar'; import Toolbar from '@mui/material/Toolbar'; import Typography from '@mui/material/Typography'; import MenuIcon from '@mui/icons-material/Menu'; import IconButton from '@mui/material/IconButton'; // 定义侧边栏宽度常量 const drawerWidth = 240; // 自定义组件改名为StyledAppBar,避免和导入的MuiAppBar重名 const StyledAppBar = styled(MuiAppBar, { shouldForwardProp: (prop) => prop !== 'open', })(({ theme, open }) => ({ zIndex: theme.zIndex.drawer + 1, transition: theme.transitions.create(['width', 'margin'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), ...(open && { marginLeft: drawerWidth, width: `calc(100% - ${drawerWidth}px)`, transition: theme.transitions.create(['width', 'margin'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.enteringScreen, }), }), })); const AppBar = () => { const [open, setOpen] = React.useState(false); const handleDrawerOpen = () => { setOpen(true); }; return ( <div> <StyledAppBar position="fixed" open={open}> <Toolbar> <IconButton color="inherit" aria-label="open drawer" onClick={handleDrawerOpen} edge="start" sx={{ marginRight: '36px', ...(open && { display: 'none' }), }} > <MenuIcon /> </IconButton> <Typography variant="h6" noWrap component="div"> Mini variant drawer </Typography> </Toolbar> </StyledAppBar> </div> ) } export default AppBar
内容的提问来源于stack exchange,提问作者Saurabh
相关产品推荐
相关产品推荐

