在多个样式的HoC上具有样式的Material UI withStyles

时间:2019-05-02 17:34:04

标签: javascript reactjs material-ui

当我将多个HoC应用于一个组件时,我的应用程序将HoC用作其模态,而我使用withStyles对其样式进行设置,但是第一个HoC的类属性将传递给该组件的下一个。

HoC1示例:

const styles = themes => ({
    HoCOneStyle: {
        margin: 'auto'
    }
})

const withHoCOne = (WrappedComponent) => {
    class HoCOne extends React.Component {
        <HoC Stuff className={classes.HoCOneStyle} />
        <WrappedComponent
        {...this.props}
        />
    }

    return withStyles(styles, {withTheme: true})(HoCOne);
}
export default withHoCOne;

HoC2示例:

const styles = themes => ({
    HoCTwoStyle: {
        margin: 'auto'
    }
})

const withHoCTwo = (WrappedComponent) => {
    class HoCTwo extends React.Component {
        <HoC Stuff className={classes.HoCTwoStyle} />
        <WrappedComponent
        {...this.props}
        />
    }

    return withStyles(styles, {withTheme: true})(HoCTwo);
}
export default withHoCTwo;

示例组件:

class DemoComponent extends React.Component {
    render() {
        return (
            <Component Stuff />
        )
    }
}

export default compose(
    withHoCOne,
    withHoCTwo
)(DemoComponent)

如果运行此代码,则会在控制台中引发错误:

  

警告:Material-UI:提供给类的键“ HoCOneStyle”   HoCTwo中未实现该属性。您只能覆盖以下其中一项   以下:HoCTwoStyle。

如何避免引发此错误?实际上,它并不能阻止任何工作,我只是不想在控制台中出现错误。

1 个答案:

答案 0 :(得分:1)

您只需要避免将classes属性从HoCOne传递到HoCTwo。在还使用classes的对象上包含withStyles属性时,它将触发Material-UI的mergeClasses功能。

您应该可以使用以下类似的方法解决此问题:

render() {
  const {classes, ...otherProps} = this.props;
  return <><HoC className={classes.HoCOneStyle} /><WrappedComponent
        {...otherProps}
        /></>;
}