React中如何为Material UI Tabs组件设置自定义样式?
问题排查
你的代码存在两个核心问题导致样式不生效:
- 定义的
styles变量没有绑定到对应DOM节点,背景色和阴影自然不会生效 TabIndicatorProps中background属性直接填primary是无效的,primary是MUI主题色的key,不是合法的CSS颜色值,只有indicatorColor属性才支持直接传主题色key
实现方案(适配MUI v5+)
推荐用MUI原生的sx属性写样式,兼顾灵活性和主题适配,修改后的代码如下:
const routes = ["/tab1", "/tab2"]; function MainNavigation() { return ( <IonToolbar > <BrowserRouter > <Route path="/" render={(history) => ( <div className="toolbar" // 这里绑定Tab栏的背景和阴影样式 sx={{ backgroundColor: "white", boxShadow: '0 2px 2px -2px rgba(0,0,0,.2)' }} > <Tabs // 指示器样式在这里配置 TabIndicatorProps={{ sx: { backgroundColor: 'primary.main', // 取主题主色,也可以直接填色值比如'#ff0000' height: '3px', // 自定义下划线高度 borderRadius: '2px 2px 0 0' // 自定义圆角,按需修改 } }} indicatorColor="primary" color="primary" variant="scrollable" scrollButtons="auto" aria-label="scrollable auto tabs" value={history.location.pathname !== "/" ? history.location.pathname : routes[1]} // 这里不要返回false,默认匹配首页跳转的路由 > <Tab className="mat-tab" label="Tab1" value={routes[1]} component={Link} to={routes[1]} // 如果需要自定义激活态Tab的文字样式,可以加sx sx={{ '&.Mui-selected': { fontWeight: 700 // 激活态加粗,按需修改 } }} ></Tab> <Tab className="mat-tab" label="Tab2" value={routes[0]} component={Link} to={routes[0]} ></Tab> </Tabs> </div> )} ></Route> <Switch > <Route path="/scutes" component={Tab2}></Route> <Route path="/gateways" component={Tab1}></Route> <Redirect exact from="/" to="/tab2" /> </Switch> </BrowserRouter> </IonToolbar> ); } export default MainNavigation; function handleTabChange(index: any) { throw new Error("Function not implemented."); }
补充说明
如果还需要修改更多样式可以直接对应MUI的类名覆盖:
- 整个Tabs容器的类是
.MuiTabs-root - 单个Tab的类是
.MuiTab-root - 激活态Tab的类是
.Mui-selected - 指示器的类是
.MuiTabs-indicator
内容的提问来源于stack exchange,提问作者Devstar34
相关产品推荐
相关产品推荐

