我们可以在 _app.js 中同时使用 MUI makeStyles 和 Theming 吗

时间:2021-03-04 15:23:23

标签: javascript reactjs material-ui next.js theming

我正在使用带有 React + Next 结构的 MUI Persistent Drawers 制作一个棘手的导航组件。为了使内容因状态更改而缩小,我不得不将整个导航系统放在 _app.js 文件中,而不是将其放在一个不同的组件中。

尽管它显然有效,但我想知道一旦构建它是否会影响渲染和性能。 makeStyles((theme) 似乎工作得很好,但在 VScode 中没有突出显示,可能是因为我同时使用了 ma​​keStylesuseThemeThemeProvider在同一个文件中,如下所示:

import { makeStyles, useTheme } from '@material-ui/core/styles';
import { ThemeProvider } from '@material-ui/core/styles';
const useStyles = makeStyles((theme) => ({ ...
    (className example:) appBarShift: {
    width: `calc(100% - ${drawerWidth}px)`,
    marginLeft: drawerWidth,
    transition: theme.transitions.create(['margin', 'width'], {
      easing: theme.transitions.easing.easeOut,
      duration: theme.transitions.duration.enteringScreen,
    }),
}, ... etc

将所有内容放在 _app.js 中是个好主意,还是我需要将所有内容重构为一个新组件,以某种方式将 props 传递给父组件?

感谢您的考虑,向大家致以最诚挚的问候

1 个答案:

答案 0 :(得分:1)

我建议您将您的主题放在文件夹 theme/theme.js 中并使用 createMuiTheme 然后在您的 app.js 中使用主题提供程序包装您的整个组件!这将在整个应用程序中传播您的主题,并让您在需要的地方使用它!是我们用 material-ui 得到的约定。

theme/theme.js:

import { createMuiTheme } from "@material-ui/core/styles"

export const themeObject = {
  palette: {
    primary: { main: "#333333" },
    secondary: { main: "#FD8C7C" },
  },
  backgroundColor: {
    primary: { main: "#FEF8F8" },
    secondary: { main: "#FFFFFF" },
  },
  breakpoints: {
    values: {
      xs: 0,
      sm: 600,
      md: 960,
      lg: 1280,
      xl: 1920,
    },
  },
  overrides: {
    MuiDivider: {
      root: {
        backgroundColor: "#FFFFFF",
      },
    },
  },
}

export default createMuiTheme(themeObject)

页面/应用程序,js:


import React from "react"
import { ThemeProvider } from "@material-ui/styles"
import Box from "@material-ui/core/Box"
import defaultTheme from "../theme/theme"

const App = () => {
  return (
    <Box>
      <ThemeProvider theme={defaultTheme}>
       ...
      </ThemeProvider>
    </Box>
  )
}

export default App

组件/SideBar.js:

import React from "react"
import { makeStyles } from "@material-ui/core/styles"

const useStyles = makeStyles((theme) => ({
  drawer: {
    width: theme.sidebar.width,
    color: theme.palette.primary
    flexShrink: 0,
    whiteSpace: "nowrap",
    "& .MuiDrawer-paper": {
      top: "unset",
    },
  },
  drawerClose: {
    transition: theme.transitions.create("width", {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.leavingScreen,
    }),
    overflowX: "hidden",
    width: theme.spacing(7) + 1,
    [theme.breakpoints.up("sm")]: {
      width: theme.spacing(7) + 1,
    },
  },
  expandButton: {
    [theme.breakpoints.up("sm")]: {
      marginLeft: theme.spacing(-2.5),
      marginRight: theme.spacing(2.5),
    },
  },
}))

export default function Sidebar(props) {
const classes = UseStyles()
  return (...)
}


在侧边栏中,您可以看到我使用了直接来自 theme.js 的 theme.zindex.drawer。 我还建议您查看此 MUI THEMING 以更深入地了解主题!