具有makeStyles的material-ui动态规则名称

时间:2019-08-28 04:49:56

标签: reactjs material-ui jss

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

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

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;
}

1 个答案:

答案 0 :(得分:3)

您可以在功能组件内部使用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