如何使用2个样式对象导出react material-ui组件? (material-ui V1)

时间:2018-02-14 17:32:35

标签: javascript reactjs material-ui

我们正在使用material-ui v1并组成HOC我们正在使用重构实用程序。问题是我们有2个样式对象。一个是在组件内部定义的,另一个是通用样式对象(在另一个jsx样式文件中定义,该文件导出系统范围内使用的javascript样式对象)。现在我们需要组合两个样式对象。有没有办法做到这一点? 使用withStyles编写2个样式对象不起作用。非常感谢任何帮助。

以下是我们的代码:

import { connect } from 'react-redux';
import { withStyles } from 'material-ui/styles';
import compose from 'recompose/compose';
import { generalStyle } from '../../modules/styles/styles';//external style object

//internal style object
const styleObj = theme => ({
  paper: {
    padding: 16,
    color: theme.palette.text.secondary,
  },
});

class myCompo extends React.Component {
//..compo code
}

//composing 2 style objects with withStyles does not work
export default compose(
  withStyles({ styleObj, generalStyle }),
  connect(mapStateToProps, mapDispatchToProps),
)(myCompo );

//here is how generalStyle is defined in styles.jsx file
const generalStyle = theme => ({
  floatR: {
    float: 'right',
  },
  floatL: {
    float: 'left',
  },
  parallelItmes: {
    display: 'flex',
    alignItems: 'center',
    padding: theme.spacing.unit,
    paddingLeft: theme.spacing.unit + 10,
  },
});

module.exports = {
  generalStyle,
};

1 个答案:

答案 0 :(得分:2)

假设您generalyStyles定义了这样的内容:

const generalStyles = theme => ({
  generalStylesButton: {
    backgroundColor: "#ff0000",
    margin: theme.spacing.unit,
  },
});

然后,您可以通过执行该功能将generalStyles合并到internalStyles中(我认为这是您根据评论中的代码段丢失的内容),然后传播结果对象:

const internalStyles = theme => ({
  internalStylesButton: {
    backgroundColor: "#00ff00",
    margin: theme.spacing.unit,
  },
  // Notice that since generalStyles is a function, not an object, you need
  // to execute it before you can merge
  ...generalStyles(theme)
});

然后可以使用两组样式的样式:

function FlatButtons(props) {
  const { classes } = props;
  return (
    <div>
      <Button className={classes.internalStylesButton}>
        Styled from internal
      </Button>
      <Button className={classes.generalStylesButton}>
        Styled from general
      </Button>
    </div>
  );
}

FlatButtons.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(internalStyles)(FlatButtons);

您可以将此逻辑封装在HOC中,以避免在每个组件中复制扩展运算符。您可能还需要注意generalStylesinternalStyles具有相同类名的情况:

const general = theme => ({
  duplicateName: {
    backgroundColor: "#ff0000",
  },
});

const internal = theme => ({
  duplicateName: {
    backgroundColor: "#00ff00",
  },
  ...general(theme),
});

让展开运算符在这两种样式之间协调duplicateName可能会导致棘手的情况。