在 MUI v5 中使用 sx prop 的最佳方式是什么?

Ali*_*azi 10 design-patterns jsx reactjs material-ui jss

我已经开始在之前的项目中将 MUI v5 与 makeStyles 一起使用。部署后,我在加载页面 CSS 时遇到了巨大的延迟。所以我开始搜索,发现makeStyles在 MUI v5 中已弃用

MUI 建议使用sxprop 代替。没关系。但这里的问题是我不想将 JSX 和 CSS/JSS 代码写在一起。例如:

MUI 是这样说的:

// App.js
function App() {
  return (
    <Grid sx={{ bgcolor: 'yellow', mx: 5, pt: 2, border: 1 }}>
      This is a test!
    </Grid>
  );
}

export default App;
Run Code Online (Sandbox Code Playgroud)

以下是我所期望的:

// style.js
export default {
  myGrid: {
    bgcolor: 'yellow',
    mx: 5,
    pt: 2,
    border: 1,
  },
};
Run Code Online (Sandbox Code Playgroud)
// App.js
import style from "./style";

function App() {
  return <Grid sx={style.myGrid}>This is a test!</Grid>;
}

export default App;
Run Code Online (Sandbox Code Playgroud)

我想知道独立使用 JSS 和 JSX 文件的最佳模式是什么sx?在另一个文件中输入 props 时是否可以获得 VSCode 建议sx

Loj*_*uka 6

看看这个:)我们可以将样式存储在单个对象中。

用于Record<Keys, Type>定义父对象类型。

之后,您在输入关键字时会收到建议。ETC:backgroundColor

https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type

//styles.ts
import { SxProps, Theme } from "@mui/material";

export const navBarStyles: Record<string, SxProps<Theme> | undefined> = {
    notification: {
        backgroundColor: 'white',
        "&:hover, &.Mui-focusVisible": { backgroundColor: "white" }
    },
    test: {
        color: 'green'
    }
}
Run Code Online (Sandbox Code Playgroud)

然后导入navBarStyles

//navbar.tsx
import { navBarStyles } from '../styles/mui/navbar';
Run Code Online (Sandbox Code Playgroud)

应用样式

//navbar.tsx
const Navbar = () => {
  return (
          <IconButton sx={navBarStyles.notification}>
            <KeyboardArrowDownRoundedIcon htmlColor='#ffffff' />
          </IconButton>
  )
}
Run Code Online (Sandbox Code Playgroud)


tim*_*son 2

您可以使用 TypeScript 来实现这一点。如果您的项目中尚未配置 TypeScript,则必须添加它(请参阅此 SO 答案以获取帮助)。

然后,您可以使用该类型创建包含所有组件样式的 styles.ts 文件SxProps

// Styles.ts
import { SxProps } from '@mui/material'

const myGrid: SxProps = {
  bgColor: 'yellow',
  mx: 5,
  pt: 2,
  border: 1
}

export default { myGrid }
Run Code Online (Sandbox Code Playgroud)

通过在 stlye 对象上使用 SxProps 类型,您将使用所有 MUI sx 属性获得代码完成。