首页 > 解决方案 > 在 makeStyles 中引用样式而不是类名连接

问题描述

我经常遇到这样的情况,我想重新使用样式定义来获得类似的效果。

假设我想要一个imageandbutton具有相同的hover效果,我会定义这样的样式:

const useStyles = makeStyles({
  hoverable: {
      transition: 'all .2s ease-in-out',
      "&:hover": {
          transform: 'scale(1.29)',
      },
  },
  img: {
      borderRadius: '10px',
  },
  btn: {
      color: 'white',
  },
});

css classes然后通过连接之前定义并通过useStyles-hook生成的所需组件在组件上使用它们:

const classes = useStyles();
<img className={`${classes.img} ${classes.hoverable}`} src={someImg} alt={someImg} />
<button className={`${classes.btn} ${classes.hoverable}`}>Ok<button />

虽然这很好用,但我最终在样式定义和组件本身之间来回跳跃,以了解应用哪些样式以及有时需要多个连接,所以这就是我想做的事情:

import {CreateCSSProperties, PropsFunc} from '@material-ui/styles/withStyles'

const hoverable: React.CSSProperties | CreateCSSProperties<{}> | PropsFunc<{}, CreateCSSProperties<{}>> = {
  transition: 'all .2s ease-in-out',
   "&:hover": {
       transform: 'scale(1.29)',
   },
}

const useStyles = makeStyles({
  img: {
      borderRadius: '10px',
      ...hoverable
  },
  btn: {
      color: 'white',
      ...hoverable
  },
});

当然,可以type为上面很长的类型串联创建一个方便的包装器 `alias,并将其导入到需要的任何地方。

由于我还没有在任何地方看到此解决方案,我想知道是否有任何理由不使用它,因为与通过class-name 连接的常见样式组合相比,它在某些情况下可能是不利的?

标签: reactjstypescriptmaterial-ui

解决方案


推荐阅读