我正在关注 mui's website 上的教程使框架的版本 5 就位。一切都很好,只是我无法弄清楚如何使样式化组件工作。
这是一个最小的示例 with a sandbox to try it out :
import React from "react";
import { render } from "react-dom";
import { createTheme, styled, ThemeProvider } from "@mui/material/styles";
import { Button } from "@mui/material";
const theme = createTheme({
palette: {
primary: {
main: "#4cfcb3",
light: "#8affe5",
dark: "#00c883",
contrastText: "#000"
},
secondary: {
main: "#00b0ff",
light: "#69e2ff",
dark: "#0081cb",
contrastText: "#FFF"
}
}
});
const Test = styled(() => <div>TEST SHOULD BE RED</div>)({
color: "red",
backgroundColor: "#000"
});
const App = () => (
<ThemeProvider theme={theme}>
<Button color="primary" variant="contained">
Hello Button
</Button>
<br />
<br />
<Test />
</ThemeProvider>
);
render(<App />, document.getElementById("app"));
在此示例中,我们可以看到按钮正确获取了主题中指定的颜色,所以这很好,但是我的 Test
样式组件根本没有像您那样设置样式参见这里:
我做错了什么?
最佳答案
你必须这样调用它 this :
基本上,您必须删除回调并仅向其传递 'div'
和具有 CSS 属性的配置对象。
要调用它,请使用组件的开始和结束标记。
import React from "react";
import { render } from "react-dom";
import { createTheme, styled, ThemeProvider } from "@mui/material/styles";
import { Button } from "@mui/material";
const theme = createTheme({
palette: {
primary: {
main: "#4cfcb3",
light: "#8affe5",
dark: "#00c883",
contrastText: "#000"
},
secondary: {
main: "#00b0ff",
light: "#69e2ff",
dark: "#0081cb",
contrastText: "#FFF"
}
}
});
const Test = styled('div')({
color: "red",
backgroundColor: "#000"
});
const App = () => (
<ThemeProvider theme={theme}>
<Button color="primary" variant="contained">
Hello Button
</Button>
<br />
<br />
<Test>TEST SHOULD BE RED</Test>
</ThemeProvider>
);
render(<App />, document.getElementById("app"));
关于reactjs - 无法让 @mui 5 样式的组件工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70813268/