Material UI 样式在组件中不起作用(警告:`@material-ui/styles` 的多个实例)

Roo*_*Roo 6 javascript css reactjs material-ui

我创建了一个使用 Material UI (4.8.3) 库的独立 React 组件,并将其发布到私有 NPM 包,以便它可以在一系列应用程序中使用。

独立组件项目工作正常(我正在使用 Storybook 来测试组件),但是当我发布组件并将其导入到新的 React 项目(使用 create-react-app 创建)时,我收到警告:

It looks like there are several instances of `@material-ui/styles` initialized in this application. This may cause theme propagation issues, broken class names, specificity issues, and makes your application bigger without a good reason.
Run Code Online (Sandbox Code Playgroud)

该组件在页面上呈现如下所示,但没有应用任何主题:

单击之前的组件

单击它时,主 React 应用程序上的任何主题都会被删除(请注意,菜单后面背景中的深蓝色条已失去颜色):

点击后的组件

我正在使用 Material UIwithStyles功能来主题化我的组件,我猜这是问题所在,因为我的主 React 应用程序也在使用它,但这是应用样式的推荐方法。是否感觉我需要以某种方式从主主机应用程序继承主题的实例?

我的组件项目是使用 create-react-library 创建的,也是使用 Rollup (0.64.1) 和 babel (6.26.3) 创建的。

这是该组件:

It looks like there are several instances of `@material-ui/styles` initialized in this application. This may cause theme propagation issues, broken class names, specificity issues, and makes your application bigger without a good reason.
Run Code Online (Sandbox Code Playgroud)

它被发布到 NPM 包,然后使用以下命令导入到主应用程序中:

import React, { Component } from 'react'
import { MyComponent } from '@xxx/mycomponent'

const styles = theme => ({
  root: {
    display: "flex",
    flexGrow: 1
  }
});

// --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Class
// --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
class App extends Component {
  //

  // --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  render() {
    //
    const { classes } = this.props;

    return (
      <div className={classes.root}>
        <MyComponent />
      </div>
    );
  }
}

export default withRouter(withStyles(styles)(App))

Run Code Online (Sandbox Code Playgroud)

小智 0

您应该在故事书中链接@material-ui/styles,因此首先需要npm link @material-ui/styles在故事书中链接,而不是在应用程序中链接