假设我希望Button
来自的每个组件material-ui
都具有variant="contained" color="secondary"
. 这可能吗?
是否可以覆盖 material-ui 组件的默认props?
IT技术
reactjs
material-ui
2021-04-22 04:31:18
3个回答
相关文档在这里:https : //material-ui.com/customization/globals/#default-props
以下是如何在 v4 中执行此操作的示例(进一步向下 v5 示例):
import React from "react";
import ReactDOM from "react-dom";
import {createMuiTheme, MuiThemeProvider, Button} from "@material-ui/core";
const theme = createMuiTheme({
props: {
MuiButton: {
variant: "contained",
color: "secondary"
}
}
});
function App() {
return (
<MuiThemeProvider theme={theme}>
<Button>Props defaulted</Button>
</MuiThemeProvider>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
这是一个类似的示例,但使用 Material-UI v5 的主题结构:
import React from "react";
import ReactDOM from "react-dom";
import Button from "@mui/material/Button";
import { createTheme, ThemeProvider } from "@mui/material/styles";
const theme = createTheme({
components: {
MuiButton: {
defaultProps: {
variant: "contained",
color: "secondary"
}
}
}
});
function App() {
return (
<ThemeProvider theme={theme}>
<Button>Props defaulted</Button>
</ThemeProvider>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
创建您自己的组件<MyButton />
,该<Button>
组件从material-ui
. 根据需要设置组件样式并MyButton
在代码中使用。
如果我正确理解了这个问题,则必须在实例化主题时进行设置:
const theme = createMuiTheme({
overrides: {
MuiButton: {
root: {
fontSize: '1rem',
},
},
},
});
其它你可能感兴趣的问题