【问题标题】:What is the best way to use sx prop in MUI v5?在 MUI v5 中使用 sx 道具的最佳方式是什么?
【发布时间】:2022-08-05 05:28:55
【问题描述】:

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

MUI 建议改用sx prop。没关系。但这里的问题是我不想将我的 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;

以下是我所期望的:

// style.js
export default {
  myGrid: {
    bgcolor: \'yellow\',
    mx: 5,
    pt: 2,
    border: 1,
  },
};
// App.js
import style from \"./style\";

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

export default App;

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

  • 您使用 style.js 文件的方式让我认为您应该研究主题(即将全局样式应用于整个应用程序)。如果您想重用样式化的 Grid 组件,那么您应该查看样式化组件。 sx 属性通常应该只用于小的调整。

标签: reactjs design-patterns material-ui jsx jss


【解决方案1】:

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

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

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

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

export default { myGrid }

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 2022-07-24
    • 2022-10-15
    • 2022-08-16
    • 1970-01-01
    相关资源
    最近更新 更多