【发布时间】:2020-07-05 21:18:24
【问题描述】:
我创建了一个使用 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.
组件呈现在页面上,如下所示,但未应用任何主题:
当点击它时,主 React App 上的所有主题都将被移除(注意菜单后面背景中的深蓝色条已失去颜色):
我正在使用 Material UI withStyles 功能来主题化我的组件,我想这是我的主要 React 应用程序也使用它的问题,但这是应用于样式的推荐方式。是否觉得我需要以某种方式从主宿主应用程序继承主题的实例?
我的组件项目是使用 create-react-library 创建的,因此也是使用 Rollup (0.64.1) 和 babel (6.26.3)。
这是组件:
import React, {Component} from 'react'
import { withStyles } from '@material-ui/core/styles'
const styles = theme => ({
root: {
fontSize: '14px',
}
})
// --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
class MyComponent extends Component {
render() {
const { classes } = this.props
return (
<div className={classes.root}>Hello world</div>
)
}
}
export default withStyles(styles)(MyComponent)
发布到 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))
【问题讨论】:
-
您的问题需要进一步澄清,请留下一些代码或链接您的问题的 CodeSandBox 复制品。
-
嗨。我已经添加了代码,但它非常基本。
-
有什么解决办法吗?
标签: javascript css reactjs material-ui