首页 > 解决方案 > 在反应中通过主题提供者的材料 UI 多种字体

问题描述

是否可以选择在主题提供程序中提供多种字体以做出反应,而不是通过钩子或其他方式动态地将其中一种字体应用于不同的元素/组件?

BR,伊戈尔

标签: reactjsmaterial-ui

解决方案


是的。您可以通过主题配置提供多种字体。

const theme = createMuiTheme({
  typography: {
    a: {
       fontFamily: "Roboto",
       fontSize: 12
    },
    b: {
       fontFamily: "Helvetica",
       fontSize: 14
    } 
  }
});

<ThemeProvider theme={theme}>
  <... />
</ThemeProvider>

在你的组件中:

const useStyles = makeStyles((theme) => ({
  textA: {
    ...theme.typography.a,
  },
  textB: {
    ...theme.typography.b,
  }
}));

const Greeting = ({useA}) => {
  const classes = useStyles();
  return <p className={useA ? classes.textA : classes.textB}>Hey</p>;
};

如果您不想创建两个类名,您也可以将属性传递给useStyles并根据此属性设置类内的字体。


推荐阅读