繁体   English   中英

如何导出具有 2 个样式对象的 react material-ui 组件? (材质-ui V1)

[英]How can I export a react material-ui component with 2 styles object? (material-ui V1)

我们正在使用 material-ui v1 并使用 recompose 实用程序来编写 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,
};

假设你有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可能会导致棘手的情况。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM