Kim*_* Vu 1 typescript reactjs material-ui
我越来越
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Palette'.
No index signature with a parameter of type 'string' was found on type 'Palette'.ts(7053)
Run Code Online (Sandbox Code Playgroud)
尝试使用字符串列表从ThemeProviderMaterial-UI获取主题时
样本是 astring[]并且包含看起来像"primary.light"or的字符串"secondary.dark"
useTheme使用这个文件:
import { createTheme, responsiveFontSizes } from '@mui/material/styles';
import { deepPurple, amber } from '@mui/material/colors';
// Create a theme instance.
let theme = createTheme({
palette: {
primary: deepPurple,
secondary: amber,
},
});
theme = responsiveFontSizes(theme);
export default theme;
Run Code Online (Sandbox Code Playgroud)
和组件:
const ColorPaletteContent = ({ content }: { content: ColorPalette }) => {
const theme = useTheme();
return (
<>
<h1>{content.title}</h1>
<div className={colorPaletteStyles.swatch_container}>
{content.swatches.map((swatch) => {
const parentColor = swatch.split('.')[0];
const childColor = swatch.split('.')[1];
return (
<div key={swatch} className={colorPaletteStyles.swatch}>
<Avatar
sx={{
bgcolor: theme.palette[parentColor][childColor],
height: 68,
width: 68,
}}
>
{''}
</Avatar>
{childColor}
</div>
);
})}
</div>
</>
);
};
Run Code Online (Sandbox Code Playgroud)
界面Palette看起来像这样,所以我知道在这里使用字符串作为键是无效的,但是如何相应地转换 myparentColor和childColor以使类型正确?:
export interface Palette {
common: CommonColors;
mode: PaletteMode;
contrastThreshold: number;
tonalOffset: PaletteTonalOffset;
primary: PaletteColor;
secondary: PaletteColor;
error: PaletteColor;
warning: PaletteColor;
info: PaletteColor;
success: PaletteColor;
grey: Color;
text: TypeText;
divider: TypeDivider;
action: TypeAction;
background: TypeBackground;
getContrastText: (background: string) => string;
augmentColor: (options: PaletteAugmentColorOptions) => PaletteColor;
}
Run Code Online (Sandbox Code Playgroud)
parentColor是any,不是 keyof Palette。要消除错误,您需要使用正确的类型对其进行断言:
// "primary" | "secondary" | "error" | "warning" | "info" | "success"
type PaletteKey = keyof {
[Key in keyof Palette as Palette[Key] extends PaletteColor ? Key : never]: true;
}
// "light" | "dark" | "main" | "contrastText"
type PaletteColorKey = keyof PaletteColor
theme.palette[parentColor as PaletteColorKey][childColor as PaletteColorKey]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1330 次 |
| 最近记录: |