【发布时间】:2026-01-09 06:15:01
【问题描述】:
我正在尝试在样式化组件中访问我的 Material-UI 主题道具,但是我不断得到...
TypeError: Cannot read property 'primary' of undefined 或浏览器中的类似错误。
这是我的自定义主题 (index.ts)
import { createMuiTheme } from "@material-ui/core";
import { blue } from "@material-ui/core/colors";
const theme = createMuiTheme({
palette: {
primary: {
main: blue[800],
contrastText: "#FFF"
},
secondary: {
main: blue[600],
contrastText: "#FFF"
}
},
typography : {
fontFamily: [
"Nunito",
"Roboto",
].join(",")
}
});
export default theme;
这是我的主题在App.tsx 中包装我的应用程序的地方
// Other imports
import theme from "../../app/theme/index";
const App: React.FC = () => {
return (
<>
<StylesProvider injectFirst>
<ThemeProvider theme={theme}>
// Routing stuff
</ThemeProvider>
</StylesProvider>
</>
);
};
export default App;
这是我尝试使用样式化组件的地方
import { ListItem } from "@material-ui/core";
import React from "react";
import styled from "styled-components";
const Brand = styled(ListItem)`
background-color: ${props => props.theme.palette.primary.dark},
padding: ${props => props.theme.spacing(1)},
font-size: ${props => props.theme.typography.h6.fontSize},
font-weight: ${props => props.theme.typography.fontWeightMedium},
color: "white",
min-height: "64px",
padding-left: ${props => props.theme.spacing(6)}
`;
const SidebarNew: React.FC = () => {
return (
<Brand button>
// Stuff
</Brand>
);
};
export default SidebarNew;
这编译但在浏览器中失败。我在这里错过了什么?
如果我使用 Material-ui 的内置 styled 如下所示,它似乎可以工作,但我更喜欢直接使用 styled-components
const Brand = styled(ListItem)(({ theme }) => ({
backgroundColor: theme.palette.primary.dark,
padding: theme.spacing(1),
fontSize: theme.typography.h6.fontSize,
fontWeight: theme.typography.fontWeightMedium,
color: "white",
minHeight: 64,
paddingLeft: theme.spacing(6)
}));
【问题讨论】:
-
除了 Material-UI
ThemeProvider之外,您还需要使用styled-componentsThemeProvider。您可以在两个提供程序中指定相同的主题。有关使用styled-componentsThemeProvider的示例,请在此处查看我的答案:*.com/questions/59921880/…。 -
根据您的链接问题的答案 - codesandbox.io/s/material-ui-theme-bhy1h,我仍然无法使用示例。我还有可能在哪里出错?会是 TypeScript 吗?
标签: reactjs typescript material-ui styled-components