TypeScript中如何设置variant为temporary的drawer组件的zIndex
实现temporary类型Drawer裁剪在AppBar下方并规避TS报错的方案
你可以通过以下两种合法方式实现需求,同时不会触发TypeScript报错:
- 方式一:使用MUI原生
sx属性声明样式
sx属性原生支持带!important后缀的属性值,无需额外类型断言即可通过TS校验,示例代码如下:
import Drawer from '@mui/material/Drawer'; import AppBar from '@mui/material/AppBar'; // 组件内使用 <AppBar position="fixed"> {/* AppBar内容 */} </AppBar> <Drawer variant="temporary" open={drawerOpen} onClose={toggleDrawer} sx={{ // 取AppBar的zIndex减1,保证Drawer在AppBar下方 zIndex: (theme) => `${theme.zIndex.appBar - 1} !important`, }} > {/* Drawer内容 */} </Drawer>
- 方式二:用styled组件封装自定义Drawer
如果需要多处复用该样式的Drawer,可以通过styled API封装,样式定义完全符合TS类型规则:
import { styled, Drawer, Theme } from '@mui/material'; const BelowAppBarDrawer = styled(Drawer)(({ theme }: { theme: Theme }) => ({ '&.MuiDrawer-root': { zIndex: `${theme.zIndex.appBar - 1} !important`, }, })); // 组件内直接使用封装后的组件 <BelowAppBarDrawer variant="temporary" open={drawerOpen} onClose={toggleDrawer}> {/* Drawer内容 */} </BelowAppBarDrawer>
两种方式都可以实现temporary类型Drawer渲染在AppBar下方的效果,无需额外的类型兼容处理。
内容的提问来源于stack exchange,提问作者Shilpa Puranik
相关产品推荐
相关产品推荐

