首页 > 解决方案 > 使样式反应 JS

问题描述

我有这个问题。我正在尝试使用 material-ui 进行网页设计,我有以下代码:

const useStyles = makeStyles((theme) => ({
  card: {
    marginTop: theme.spacing(10),
    direction:"column",
    alignItems:"center",
    justify:"center",
    borderRadius: 30,
    boxShadow: ' 0 14px 28px rgba(0,0,0,0.25), 0 10px 10px rgba(0,0,0,0.22)',
    },
  contenidoFormulario: {
    marginTop: theme.spacing(8),
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
  },
  avatar: {
    margin: theme.spacing(1),
    backgroundColor: theme.palette.primary.main,
  },
  formulario: {
    width: '60%',
    marginTop: theme.spacing(1),
  },
  botonIngresar: {
    margin: theme.spacing(3, 0, 2),
    borderRadius: 50,
  },
}));

而且我在三个不同的组件(Login.js、Newaccount.js、Forgotpassword.js)中使用它,如何重复使用它以避免重复相同的代码?

标签: javascriptreactjsmaterial-ui

解决方案


您可以创建一个类似的文件commonStyles.js并导出您的样式。在其他组件中,您只需要导入此样式并在您的组件中调用它。通过本期官方文档了解更多关于在 MUI 中组合样式的信息。尝试这个:

commonStyles.js

...
export const commonStyles= makeStyles((theme) => ({
  card: {
    marginTop: theme.spacing(10),
    direction:"column",
    alignItems:"center",
    justify:"center",
    borderRadius: 30,
    boxShadow: ' 0 14px 28px rgba(0,0,0,0.25), 0 10px 10px rgba(0,0,0,0.22)',
    },
  contenidoFormulario: {
    marginTop: theme.spacing(8),
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
  },
  avatar: {
    margin: theme.spacing(1),
    backgroundColor: theme.palette.primary.main,
  },
  formulario: {
    width: '60%',
    marginTop: theme.spacing(1),
  },
  botonIngresar: {
    margin: theme.spacing(3, 0, 2),
    borderRadius: 50,
  },
}));

Login.js

import {commonStyles} from '../commonStyles'
import {makeStyles} from '@material-ui/core/styles'

const useStyles = makeStyles(theme => ({
  ...
  
}))


const Login = () => {
  const classes = useStyles()
  const commons = commonStyles()
  return (
    <div className={commons.card}>
      ...
    </div>
  )
}

export default Login


推荐阅读