【问题标题】:In Mui, how do I use theme values in my css在 Mui 中,如何在我的 css 中使用主题值
【发布时间】:2021-10-05 10:47:05
【问题描述】:

我的 React 应用正在使用 mui 主题; index.js 包含:

let theme = createTheme({
  palette: {
    primary: {
      main: "#00aaa0",
      contrastText: '#fcf4d9',
    },
    secondary: {
      main: "#D55B3E",
      contrastText: '#fcf4d9',
    },
  },
});

theme = responsiveFontSizes(theme);

ReactDOM.render(
    <ThemeProvider theme={theme}>
      <CssBaseline />
      <App />
    </ThemeProvider>
  document.getElementById('root')
);

在我的一个组件(页脚)中,我希望能够添加一个原色的顶部边框。到目前为止,footer.tsx 包含:

const Footer= () => {

  return (
    <div className="pageFooter">Footer Text</div>
  );
};

export default Footer;

我想设置“pageFooter”的样式,以便它使用 theme.palette.primary.main 作为顶部边框颜色。使用常规 css,我将链接到我的 css 文件中,其中包含:

.pageFooter {
  border-top: 2px solid "#00aaa0";
}

但我想确保颜色始终与原色相同,所以我想做这样的事情:

.pageFooter {
  border-top: 2px solid theme.palette.primary.main;
}

不过,这不起作用,可能是因为 css 文件无法使用该主题。我已经阅读了文档,但我无法真正遵循它们。谁能解释一下我应该在这里做什么?

【问题讨论】:

  • 暂无官方支持。看看this 问题。

标签: css reactjs material-ui


【解决方案1】:
import { makeStyles } from '@material-ui/core'

const useStyles = makeStyles(theme => ({ 
   pageFooter: {
     borderColor: theme.palette.primary.main,
   }
});

const Footer= () => {
    const classes = useStyles()

  return (
    <div className={classes.pageFooter}>Footer Text</div>
  );
};

export default Footer;

【讨论】:

  • 谢谢!这解决了它。请注意:我必须使用 import { makeStyles } from "@mui/styles";(而不是 @material-ui/core),因为我使用的是 mui 而不是 material-ui。
  • 还必须通过 const useStyles:anymakeStyles((theme:any) 才能通过 TypeScript 检查
【解决方案2】:

根据 MUI 文档:

@mui/styles 是 MUI 的传统样式解决方案。它依赖于 JSS 作为样式解决方案,在 @mui/material 中不再使用,在 v5 中已弃用。

还有

@mui/styles 与 React.StrictMode 或 React 18 不兼容。

MUI 使用 JSS 进行样式设置。所以我们无法访问 CSS 文件中的主题。 我的解决方案: 您可以定义与主题调色板颜色相同的 CSS 变量。然后在 CSS 文件中使用它。

:root {
    --primary-main: #00aaa0;
  }
.pageFooter {
  border-top: 2px solid var(--primary-main);
}

【讨论】:

    猜你喜欢
    • 2022-11-17
    • 2022-01-07
    • 1970-01-01
    • 2018-12-24
    • 2019-12-20
    • 2022-10-24
    • 1970-01-01
    • 2023-02-10
    • 1970-01-01
    相关资源
    最近更新 更多