Material-ui 动态规则名称与 makeStyles

Tug*_*ain 1 reactjs material-ui jss

是否可以使用makeStyles和动态生成规则名称props

我没有看到任何方法可以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;
  };
});
Run Code Online (Sandbox Code Playgroud)

结果会是这样的:

checked: {},
rdoQA: {
  color: '#FF9800',
  '&$checked': {
    color: '#FF9800'
  }
},
rdoLive: {
  color: '#c62828',
  '&$checked': {
    color: '#c62828'
  }
}
Run Code Online (Sandbox Code Playgroud)

最终工作代码:

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);
  ...
}
Run Code Online (Sandbox Code Playgroud)

由此产生的样式

.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;
}
Run Code Online (Sandbox Code Playgroud)

Jos*_* D. 5

您可以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

Run Code Online (Sandbox Code Playgroud)