javascript - 透過模塊擴充延伸 Material UI 主題無法運作
我正在嘗試向調色板中的背景欄位添加一個「input」屬性,然後擴充主題以考慮類型,如下所示:
export const lightTheme = createTheme(commonTheme, {
palette: {
mode: 'light',
background: {
default: '#FFFFFF',
input: '#0000BB',
...
}
declare module '@mui/material/styles' {
interface Theme {
background: {
input: React.CSSProperties['color'];
};
}
interface ThemeOptions {
background: {
input: React.CSSProperties['color'];
};
}
}
然而,當我嘗試透過 color: theme.palette.background.input 訪問背景時,我收到一個錯誤:
Property 'input' does not exist on type 'TypeBackground'.為什麼增強不會將類型添加到背景屬性?
此外,我也試過這個,但沒有改變任何東西:
declare module "@mui/material/styles/createPalette" {
interface CommonColors {
background: {
input: React.CSSProperties['color'];
}
}
}
答案#1
你只需要像下面這樣擴展 TypeBackground 類型:
declare module '@mui/material/styles' {
interface TypeBackground {
input: string;
}
}
然後為 background.input 配置一個新值
const theme = createTheme({
....
palette: {
background: {
input: "#f60"
}
}
...
});
最後,我們可以這樣使用它:
<Box sx={{ bgcolor: "background.input", width: 100, height: 100 }} />
演示連結
