在 MUI 中设置排版文本颜色

新手上路,请多包涵

我对 MUI 很陌生,我正在尝试设置一个 Typography 文本颜色如下:

 const theme = createMuiTheme({
  palette: {
    text:{
      primary: "#FFFFFF"
    }
  }
});

const WhiteText = (props: { text:string, varient: Variant | 'inherit'}) => {
  return <ThemeProvider theme={theme}>
      <Typography variant={props.varient} align="center" color="textPrimary">{props.text}</Typography>
  </ThemeProvider>
}
...
<WhiteText varient="h3" text="This text should be white"/>

但文字不会改变颜色:/

我是否应用了错误的主题?

原文由 Tim 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答

尽管您的方法在 此沙箱 中运行良好,但这不是我推荐的方法。而不是嵌套主题,对于这样的自定义,我建议使用 withStyles 如下所示(对于 Material-UI 的 v4 - v5 示例进一步向下)。

 import React from "react";
import { withStyles } from "@material-ui/core/styles";
import Typography from "@material-ui/core/Typography";

const WhiteTextTypography = withStyles({
  root: {
    color: "#FFFFFF"
  }
})(Typography);

export default function App() {
  return (
    <div className="App" style={{ backgroundColor: "black" }}>
      <WhiteTextTypography variant="h3">
        This text should be white
      </WhiteTextTypography>
    </div>
  );
}

编辑白色文本


在 v5 中,MUI 显着增强了 color (对于所有具有 color 的组件)以支持主题调色板中的任何颜色,因此对于白色,您可以使用 common.white

 import React from "react";
import Typography from "@mui/material/Typography";

export default function App() {
  return (
    <div className="App" style={{ backgroundColor: "black" }}>
      <Typography variant="h3" color="common.white">
        This text should be white
      </Typography>
    </div>
  );
}

编辑白色文本

相关答案: 您可以在 Material UI 中添加额外的颜色吗?

原文由 Ryan Cogswell 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果你想为所有 Typography 元素设置默认颜色,但不为其他 Material UI 元素设置默认颜色,你可以试试这个:

 const theme = createMuiTheme({
  typography: {
    allVariants: {
      color: "pink"
    },
  },
});

原文由 PrzemKon 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进