javascript - Material UI withStyles on multiple styled HoCs

标签 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)

如果运行此代码会在控制台中抛出错误:

Warning: Material-UI: the key 'HoCOneStyle' provided to the classes property is not implemented in HoCTwo. You can only override one of the following: HoCTwoStyle.

如何避免抛出此错误?它实际上并没有阻止任何工作我只是不想在我的控制台中出现错误。

最佳答案

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

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

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

关于javascript - Material UI withStyles on multiple styled HoCs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55957554/

相关文章:

reactjs - 为 React 中的 function prop 提供默认值

javascript - ReactJS 中的导出(默认)类

javascript - React 如何扩大间距

reactjs - Material UI 的 Tooltip - 自定义风格

reactjs - React Pro 侧边栏

javascript - 如何带参数请求静态资源?

javascript - 使用 javascript 验证 .net 页面

javascript - Azure documentdb如何开发服务端?

JavaScript 组合函数

reactjs - React/Redux/Typescript - useDispatch 和 .then().catch()