MUI v5 自定义TabPanel组件使用sx prop出现TypeScript类型错误怎么办?
问题原因
你自定义的TabPanel组件的类型定义TabPanelProps未包含MUIsx属性的类型声明,同时你透传额外属性的目标是原生div,原生DOM元素本身不支持MUI的sx属性,因此触发TypeScript类型报错。
推荐解决方案
将TabPanel组件根节点的原生div替换为MUI的Box组件,同时让TabPanelProps继承Box的属性类型即可。Box是MUI原生支持sx属性的基础组件,不需要额外处理样式转换,修改后的完整代码如下:
/* eslint-disable react/require-default-props */ import * as React from 'react'; import Tabs from '@mui/material/Tabs'; import Tab from '@mui/material/Tab'; import Typography from '@mui/material/Typography'; import Box, { BoxProps } from '@mui/material/Box'; // 扩展Box的属性类型,自动包含sx等MUI通用属性的类型定义 interface TabPanelProps extends BoxProps { children?: React.ReactNode; index: number; value: number; } function TabPanel(props: TabPanelProps) { const { children, value, index, ...other } = props; return ( // 替换原生div为Box组件,支持sx属性解析 <Box role="tabpanel" hidden={value !== index} id={`simple-tabpanel-${index}`} aria-labelledby={`simple-tab-${index}`} {...other} > {value === index && ( <Box sx={{ p: 3 }}> <Typography>{children}</Typography> </Box> )} </Box> ); } function a11yProps(index: number) { return { id: `simple-tab-${index}`, 'aria-controls': `simple-tabpanel-${index}` }; } export default function MenteeVolunteerTabs() { const [value, setValue] = React.useState(0); const handleChange = (event: React.SyntheticEvent, newValue: number) => { setValue(newValue); }; return ( <Box sx={{ width: '100%' }}> <Box sx={{ borderBottom: 1, borderColor: 'divider' }}> <Tabs value={value} onChange={handleChange} aria-label="basic tabs example"> <Tab label="Volunteer" {...a11yProps(0)} /> <Tab label="Mentee" {...a11yProps(1)} /> </Tabs> </Box> <TabPanel value={value} index={0} sx={{ backgroundColor: '#F4F6F7' }}> Item One </TabPanel> <TabPanel value={value} index={1}> Item Two </TabPanel> </Box> ); }
可选方案(保留原生div)
如果你坚持使用原生div作为根节点,可手动添加sx类型声明并配合styled工具处理样式:
- 导入相关依赖:
import { SxProps, Theme, styled } from '@mui/material/styles';
- 扩展类型定义:
interface TabPanelProps { children?: React.ReactNode; index: number; value: number; sx?: SxProps<Theme>; }
- 创建支持sx的样式化div:
const StyledTabPanelRoot = styled('div')<{ sx?: SxProps<Theme> }>({});
- 组件内用
StyledTabPanelRoot替换原有div,透传所有属性即可。
内容的提问来源于stack exchange,提问作者Dijiflex
相关产品推荐
相关产品推荐

