跳到内容
+

从 JSS 迁移 (可选)

本指南解释了当从 Material UI v4 更新到 v5 时,如何从 JSS 迁移到 Emotion。

Material UI v5 迁移

  1. 开始
  2. 重大更改第一部分:样式和主题
  3. 重大更改第二部分:组件
  4. 从 JSS 迁移 👈 您在这里
  5. 故障排除

从 JSS 迁移到 Emotion

v5 中最大的变化之一是用 Emotion(或 styled-components 作为替代方案)替换 JSS 作为默认样式解决方案。

请注意,即使迁移到 v5 后,您仍然可以继续使用 JSS 为组件添加覆盖 (例如 makeStyles, withStyles)。然后,如果您想在任何时候迁移到新的样式引擎,您可以逐步重构您的组件。

本文档回顾了从 JSS 迁移所需的所有步骤。

虽然您可以使用以下两种选项中的任何一种,但第一种被认为是更可取的

1. 使用 styled 或 sx API

代码模组

我们提供了一个 代码模组 来帮助将 JSS 样式迁移到 styled API,但是这种方法会增加 CSS 的特异性。

npx @mui/codemod@latest v5.0.0/jss-to-styled <path>

示例转换

 import Typography from '@mui/material/Typography';
-import makeStyles from '@mui/styles/makeStyles';
+import { styled } from '@mui/material/styles';

-const useStyles = makeStyles((theme) => ({
-  root: {
-    display: 'flex',
-    alignItems: 'center',
-    backgroundColor: theme.palette.primary.main
-  },
-  cta: {
-    borderRadius: theme.shape.radius
-  },
-  content: {
-    color: theme.palette.common.white,
-    fontSize: 16,
-    lineHeight: 1.7
-  },
-}))
+const PREFIX = 'MyCard';
+const classes = {
+  root: `${PREFIX}-root`,
+  cta: `${PREFIX}-cta`,
+  content: `${PREFIX}-content`,
+}
+const Root = styled('div')(({ theme }) => ({
+  [`&.${classes.root}`]: {
+    display: 'flex',
+    alignItems: 'center',
+    backgroundColor: theme.palette.primary.main
+  },
+  [`& .${classes.cta}`]: {
+    borderRadius: theme.shape.radius
+  },
+  [`& .${classes.content}`]: {
+    color: theme.palette.common.white,
+    fontSize: 16,
+    lineHeight: 1.7
+  },
+}))

 export const MyCard = () => {
-  const classes = useStyles();
   return (
-    <div className={classes.root}>
+    <Root className={classes.root}>
       {/* The benefit of this approach is that the code inside Root stays the same. */}
       <Typography className={classes.content}>...</Typography>
       <Button className={classes.cta}>Go</Button>
-    </div>
+    </Root>
   )
 }

手动

我们建议使用 sx API 而不是 styled 来创建响应式样式或覆盖次要 CSS。 在此处阅读有关 sx 的更多信息

 import Chip from '@mui/material/Chip';
-import makeStyles from '@mui/styles/makeStyles';
+import Box from '@mui/material/Box';

-const useStyles = makeStyles((theme) => ({
-  wrapper: {
-    display: 'flex',
-  },
-  chip: {
-    padding: theme.spacing(1, 1.5),
-    boxShadow: theme.shadows[1],
-  }
-}));

 function App() {
-  const classes = useStyles();
   return (
-    <div className={classes.wrapper}>
-      <Chip className={classes.chip} label="Chip" />
-    </div>
+    <Box sx={{ display: 'flex' }}>
+      <Chip label="Chip" sx={{ py: 1, px: 1.5, boxShadow: 1 }} />
+    </Box>
   );
 }

在某些情况下,您可能希望在一个文件中创建多个 styled 组件,而不是增加 CSS 特异性。

例如

-import makeStyles from '@mui/styles/makeStyles';
+import { styled } from '@mui/material/styles';

-const useStyles = makeStyles((theme) => ({
-  root: {
-    display: 'flex',
-    alignItems: 'center',
-    borderRadius: 20,
-    background: theme.palette.grey[50],
-  },
-  label: {
-    color: theme.palette.primary.main,
-  }
-}))
+const Root = styled('div')(({ theme }) => ({
+  display: 'flex',
+  alignItems: 'center',
+  borderRadius: 20,
+  background: theme.palette.grey[50],
+}))

+const Label = styled('span')(({ theme }) => ({
+  color: theme.palette.primary.main,
+}))

 function Status({ label }) {
-  const classes = useStyles();
   return (
-    <div className={classes.root}>
-      {icon}
-      <span className={classes.label}>{label}</span>
-    </div>
+    <Root>
+      {icon}
+      <Label>{label}</Label>
+    </Root>
   )
 }

2. 使用 tss-react

此 API 类似于 JSS makeStyles,但在底层,它使用 @emotion/react。它还具有比 v4 的 makeStyles 更好的 TypeScript 支持。

为了使用它,您需要将其添加到项目的依赖项中

使用 npm

npm install tss-react

使用 yarn

yarn add tss-react

代码模组

我们提供了一个 代码模组 来帮助将 JSS 样式迁移到 tss-react API。

npx @mui/codemod@latest v5.0.0/jss-to-tss-react <path>

示例转换

 import * as React from 'react';
-import makeStyles from '@material-ui/styles/makeStyles';
+import { makeStyles } from 'tss-react/mui';
 import Button from '@mui/material/Button';
 import Link from '@mui/material/Link';

-const useStyles = makeStyles((theme) => {
+const useStyles = makeStyles()((theme) => {
   return {
     root: {
       color: theme.palette.primary.main,
     },
     apply: {
       marginRight: theme.spacing(2),
     },
   };
 });

 function Apply() {
-  const classes = useStyles();
+  const { classes } = useStyles();

   return (
     <div className={classes.root}>
       <Button component={Link} to="https://support.mui.com" className={classes.apply}>
         Apply now
       </Button>
     </div>
   );
 }

 export default Apply;

如果您正在使用 $ 语法和 clsx 来组合多个 CSS 类,则转换将如下所示

 import * as React from 'react';
-import { makeStyles } from '@material-ui/core/styles';
-import clsx from 'clsx';
+import { makeStyles } from 'tss-react/mui';

-const useStyles = makeStyles((theme) => ({
+const useStyles = makeStyles<void, 'child' | 'small'>()((theme, _params, classes) => ({
   parent: {
     padding: 30,
-    '&:hover $child': {
+    [`&:hover .${classes.child}`]: {
       backgroundColor: 'red',
     },
   },
   small: {},
   child: {
     backgroundColor: 'blue',
     height: 50,
-    '&$small': {
+    [`&.${classes.small}`]: {
       backgroundColor: 'lightblue',
       height: 30
     }
   },
 }));

 function App() {
-  const classes = useStyles();
+  const { classes, cx } = useStyles();
   return (
     <div className={classes.parent}>
       <div className={classes.child}>
         Background turns red when the mouse hovers over the parent.
       </div>
-      <div className={clsx(classes.child, classes.small)}>
+      <div className={cx(classes.child, classes.small)}>
         Background turns red when the mouse hovers over the parent.
         I am smaller than the other child.
       </div>
     </div>
   );
 }

 export default App;

以下是使用 $ 语法、useStyles() 参数、从 classes prop 合并类(参见文档)以及为样式表显式命名的综合示例。

-import clsx from 'clsx';
-import { makeStyles, createStyles } from '@material-ui/core/styles';
+import { makeStyles } from 'tss-react/mui';

-const useStyles = makeStyles((theme) => createStyles<
-  'root' | 'small' | 'child', {color: 'primary' | 'secondary', padding: number}
->
-({
-  root: ({color, padding}) => ({
+const useStyles = makeStyles<{color: 'primary' | 'secondary', padding: number}, 'child' | 'small'>({name: 'App'})((theme, { color, padding }, classes) => ({
+  root: {
     padding: padding,
-    '&:hover $child': {
+    [`&:hover .${classes.child}`]: {
       backgroundColor: theme.palette[color].main,
     }
-  }),
+  },
   small: {},
   child: {
     border: '1px solid black',
     height: 50,
-    '&$small': {
+    [`&.${classes.small}`]: {
       height: 30
     }
   }
-}), {name: 'App'});
+}));

 function App({classes: classesProp}: {classes?: any}) {
-  const classes = useStyles({color: 'primary', padding: 30, classes: classesProp});
+  const { classes, cx } = useStyles({
+    color: 'primary',
+    padding: 30
+  }, {
+    props: {
+      classes: classesProp
+    }
+  });

   return (
     <div className={classes.root}>
       <div className={classes.child}>
         The Background take the primary theme color when the mouse hovers the parent.
       </div>
-      <div className={clsx(classes.child, classes.small)}>
+      <div className={cx(classes.child, classes.small)}>
         The Background take the primary theme color when the mouse hovers the parent.
         I am smaller than the other child.
       </div>
     </div>
   );
 }

 export default App;

运行代码模组后,在您的代码中搜索 “TODO jss-to-tss-react codemod” 以查找代码模组无法可靠处理的情况。

可能存在超出带有 TODO 注释的其他情况,这些情况未被代码模组完全处理——特别是当样式的某些部分由函数返回时。

如果埋藏在函数中的样式使用 $ 语法或 useStyles 参数,则这些样式将无法正确迁移。

为了确保您的类名始终包含组件的实际名称,您可以将 name 作为隐式命名的键提供 (name: { App })。

有关详细信息,请参见此 tss-react 文档

如果您解构多个项目,您可能会遇到像这样的 eslint 警告。

不要犹豫禁用 eslint(prefer-const)像这样在常规项目中,或者像这样在 CRA 中。

withStyles()

tss-react 还具有 类型安全实现v4 的 withStyles()

-import Button from '@material-ui/core/Button';
+import Button from '@mui/material/Button';
-import withStyles from '@material-ui/styles/withStyles';
+import { withStyles } from 'tss-react/mui';

 const MyCustomButton = withStyles(
+  Button,
   (theme) => ({
     root: {
       minHeight: '30px',
     },
     textPrimary: {
       color: theme.palette.text.primary,
     },
     '@media (min-width: 960px)': {
       textPrimary: {
         fontWeight: 'bold',
       },
     },
   }),
-)(Button);
+);

 export default MyCustomButton;

主题样式覆盖

全局主题覆盖 由 TSS 开箱即用地支持。

按照重大更改文档相关部分的说明进行操作,并为 makeStyles 提供一个 name

在 Material UI v5 中,样式覆盖也接受回调

默认情况下,TSS 只能提供主题。如果您想提供 props 和 ownerState请参考此文档

完成迁移

一旦您迁移了所有样式,请卸载软件包以删除不必要的 @mui/styles

使用 npm

npm uninstall @mui/styles

使用 yarn

yarn remove @mui/styles