【问题标题】:material-ui dynamic rule names with makeStyles使用 makeStyles 的 material-ui 动态规则名称
【发布时间】:2019-08-28 04:49:56
【问题描述】:

是否可以使用makeStylesprops 动态生成规则名称?

我在makeStyles 的正文中看不到任何访问props 的方法。我需要这样的东西:

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

const useStyles = makeStyles(theme => {
  return props => {
    let newObj = {
      checked: {}
    };
    props.environments.forEach(a => {
      newObj = {
        ...newObj,
        ...{
          ['rdo' + a.name]: {
            color: a.color,
            '&$checked': {
              color: a.color
            }
          }
        }
      };
    });
    return newObj;
  };
});

结果会是这样的:

checked: {},
rdoQA: {
  color: '#FF9800',
  '&$checked': {
    color: '#FF9800'
  }
},
rdoLive: {
  color: '#c62828',
  '&$checked': {
    color: '#c62828'
  }
}

最终工作代码:

const initStyles = props => {
  let newObj = {
    checked: {}
  };
  props.environments.forEach(a => {
    newObj = {
      ...newObj,
      ...{
        [`rdo${a.name}`]: {
          color: a.color,
          '&$checked': {
            color: a.color
          }
        }
      }
    };
  });
  return makeStyles(newObj)(); // note that we execute the iife
};

export default function Home(props) {
  const classes = initStyles(props);
  ...
}

生成的样式

.makeStyles-rdoQA-326 {
  color: #FF9800;
}
.makeStyles-rdoQA-326.makeStyles-checked-325 {
  color: #FF9800;
}
.makeStyles-rdoLIVE-327 {
  color: #c62828;
}
.makeStyles-rdoLIVE-327.makeStyles-checked-325 {
  color: #c62828;
}
.makeStyles-rdoSTAGE-328 {
  color: #289e59;
}
.makeStyles-rdoSTAGE-328.makeStyles-checked-325 {
  color: #289e59;
}

【问题讨论】:

  • MUI 在他们的源代码中为makeStyles 中的每种可能情况编写单独的类名,然后在他们使用clsx 的组件中根据道具决定使用哪个className。你可以查看他们的 github,查看任何将 emuns 用于 props 的组件的源代码,例如 Button

标签: reactjs material-ui jss


【解决方案1】:

您可以在函数组件中使用props

import { makeStyles } from '@material-ui/core/styles';
import environments from './someEnvironment.js'

const initStyles = (props) => {
  let newObj = {
    checked: {},
  };
  const styles = props.environments.map(a => ({
    ...newObj,
    ['rdo' + a.name]: {
      color: a.color,
      '&$checked': {
        color: a.color
      }
    }
  });

  return makeStyles(styles); // returns a hook
}

const useStyles = initStyles(environments); // pass environments as props

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-12
    • 1970-01-01
    • 2023-02-08
    • 2020-08-04
    • 2021-09-06
    • 2020-07-10
    • 2021-07-28
    相关资源
    最近更新 更多