【问题标题】:Material UI withStyles on multiple styled HoCsMaterial UI withStyles 在多个样式化的 HoC 上
【发布时间】:2019-09-21 06:38:53
【问题描述】:

我的应用程序使用 HoC 作为它的模态,我使用 withStyles 来设置它们的样式,当我将多个 HoC 应用到一个组件时,第一个 HoC 的 classes 属性在组件的组合中被传递给下一个。

示例 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。

如何避免引发此错误?它实际上并没有阻止任何东西的工作我只是不希望我的控制台出现错误。

【问题讨论】:

    标签: javascript reactjs material-ui


    【解决方案1】:

    您只需要避免将 classes 属性从 HoCOne 传递到 HoCTwo。当你在同样使用withStyles 的东西上包含classes 属性时,它会触发Material-UI 的mergeClasses 功能。

    您应该能够通过以下方式解决此问题:

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

    【讨论】:

      猜你喜欢
      • 2018-11-20
      • 2019-11-21
      • 2019-06-14
      • 2020-11-16
      • 1970-01-01
      • 2021-01-04
      • 2019-07-20
      • 2019-09-20
      • 2020-06-21
      相关资源
      最近更新 更多