如何在BottomNavigation外使用选中状态的BottomNavigationAction并通过TS校验
直接传递selected属性触发TypeScript错误的原因是:该属性并非BottomNavigationAction的公开API,它是BottomNavigation组件内部用来传递选中状态的私有属性,因此不被TypeScript类型定义所允许。
要实现符合TypeScript校验的选中状态,可通过以下两种方式实现:
方式一:内联sx样式直接控制
通过React状态管理选中项,动态设置样式和标签显示状态:
import { useState } from 'react'; import BottomNavigationAction from '@mui/material/BottomNavigationAction'; import EmailIcon from '@mui/icons-material/Email'; import CallIcon from '@mui/icons-material/Call'; const Test = () => { const [selectedValue, setSelectedValue] = useState('email'); return ( <> <BottomNavigationAction label="Email" icon={<EmailIcon />} value="email" onClick={() => setSelectedValue('email')} // 控制标签显示 showLabel={selectedValue === 'email'} // 动态设置选中样式 sx={{ color: selectedValue === 'email' ? 'primary.main' : 'text.secondary', '&:hover': { color: selectedValue === 'email' ? 'primary.dark' : 'text.primary', }, }} /> <BottomNavigationAction label="Call" icon={<CallIcon />} value="call" onClick={() => setSelectedValue('call')} showLabel={selectedValue === 'call'} sx={{ color: selectedValue === 'call' ? 'primary.main' : 'text.secondary', '&:hover': { color: selectedValue === 'call' ? 'primary.dark' : 'text.primary', }, }} /> </> ); }; export default Test;
方式二:自定义Styled组件复用样式
如果需要在多处使用,可通过styled封装带有选中样式逻辑的自定义组件:
import { useState } from 'react'; import BottomNavigationAction from '@mui/material/BottomNavigationAction'; import EmailIcon from '@mui/icons-material/Email'; import CallIcon from '@mui/icons-material/Call'; import { styled } from '@mui/material/styles'; // 封装选中样式,过滤自定义属性避免传递给DOM const StyledNavAction = styled(BottomNavigationAction, { shouldForwardProp: (prop) => prop !== 'isSelected', })(({ theme, isSelected }) => ({ color: isSelected ? theme.palette.primary.main : theme.palette.text.secondary, '&:hover': { color: isSelected ? theme.palette.primary.dark : theme.palette.text.primary, }, })); const Test = () => { const [selectedValue, setSelectedValue] = useState('email'); return ( <> <StyledNavAction label="Email" icon={<EmailIcon />} value="email" onClick={() => setSelectedValue('email')} showLabel={selectedValue === 'email'} isSelected={selectedValue === 'email'} /> <StyledNavAction label="Call" icon={<CallIcon />} value="call" onClick={() => setSelectedValue('call')} showLabel={selectedValue === 'call'} isSelected={selectedValue === 'call'} /> </> ); }; export default Test;
关键说明
showLabel是BottomNavigationAction的公开API,用于控制标签的显示/隐藏,正好对应选中时显示标签的需求。- 通过状态管理选中项,动态切换样式和
showLabel的值,既符合TypeScript类型校验要求,也能实现和BottomNavigation内部一致的选中视觉效果。
内容的提问来源于stack exchange,提问作者amay
相关产品推荐
相关产品推荐

