gpt4 book ai didi

javascript - MUI : cannot override fontFamily through theme nesting

转载 作者:行者123 更新时间:2023-12-05 04:42:51 28 4
gpt4 key购买 nike

我正在尝试让我的应用程序的不同部分使用不同的字体。我想通过主题嵌套来实现:https://mui.com/styles/advanced/#theme-nesting .

但是主题嵌套在覆盖字体时不起作用。

应用程序.js:

import React from "react";
import { ThemeProvider, Button, Typography } from "@mui/material";
import outerTheme from "./outerTheme";
import innerTheme from "./innerTheme";

const App = () => {
return (
<ThemeProvider theme={outerTheme}>
<Button>outer</Button>
<Typography color="primary">outer</Typography>
<ThemeProvider theme={innerTheme}>
<Button>inner</Button>
<Typography color="primary">inner</Typography>
</ThemeProvider>
</ThemeProvider>
);
};

export default App;

outerTheme.js:

import { createTheme } from "@mui/material";

const outerTheme = createTheme({
palette: {
primary: {
main: "#ff0000",
},
},
typography: {
fontFamily: "sans-serif",
},
});

export default outerTheme;

innerTheme.js:

import { createTheme } from "@mui/material";
import outerTheme from "./outerTheme";

const innerTheme = createTheme(outerTheme, {
palette: {
primary: {
main: "#0000ff",
},
},
typography: {
fontFamily: "serif",
},
});

export default innerTheme;

结果显示所有按钮和排版都使用外部主题的字体(即无衬线字体),但使用正确的相应主题颜色。

最佳答案

嵌套主题有效,只是您的 fontFamily 从未在第一时间设置。如果要覆盖 Button 的字体系列,需要在 typography.button.fontFamily 中设置值,而不是 typography.fontFamily ( Source ):

const outerTheme = createTheme({
typography: {
button: {
fontFamily: 'sans-serif',
},
},
});

const innerTheme = createTheme(outerTheme, {
typography: {
button: {
fontFamily: 'serif',
},
},
});

编辑:要覆盖所有 MUI 组件的 fontFamily,您需要更新所有变体:

function createFontFamily(fontFamily) {
return {
h1: { fontFamily },
h2: { fontFamily },
h3: { fontFamily },
h4: { fontFamily },
h5: { fontFamily },
h6: { fontFamily },
subtitle1: { fontFamily },
subtitle2: { fontFamily },
body1: { fontFamily },
body2: { fontFamily },
button: { fontFamily },
caption: { fontFamily },
overline: { fontFamily },
};
}
const outerTheme = createTheme({
typography: createFontFamily('sans-serif'),
});
const innerTheme = createTheme(outerTheme, {
typography: createFontFamily('serif'),
});

Codesandbox Demo

关于javascript - MUI : cannot override fontFamily through theme nesting,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69763452/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com