reactjs - 组件样式是否可以限定范围而不是内联以防止同一页面上的多个 React 应用程序覆盖?
问题描述
我有一个带有 html 的应用程序:
<div id="react-root-navbar"></div>
<div id="react-root-body"></div>
以及调用React.DOM.render
每个 div 的相应 React 组件。
两个 React 组件都使用 Material UI 组件。因此,为每个组件注入了一组内联样式。
问题是第二个组件的所有样式在 HTML 中都比第一个组件更靠后,因此这些 CSS 规则将具有更高的优先级。这会中断预期的级联流程并导致许多不正确的样式。例如,.MuiAppBar-colorPrimary
被 否决.MuiPaper-root
:
我知道理想的解决方案是将所有组件都放在一个 React 应用程序中,并首先防止重复导入。然而,这对于我正在使用的代码库是不可能的,它使用 Django 前端一次将一个迁移到 React。
有没有办法让 Material UI 为每个组件导出的样式专门针对该组件,以便样式不会相互覆盖?
解决方案
MUI has a component StylesProvider
that allows you to adjust how styles are added. StylesProvider
has a prop generateClassName
to which you can pass a generator to determine how class names are generated.
You can create a generator using a MUI function createGenerateClassName
, to which you can pass the option disableGlobal
to add simple suffixes to class names so that each app will have scoped CSS applied to it.
I was already wrapping all MUI components in a component MUIThemeProvider
to use the MUI component ThemeProvider
. I just added StylesProvider
to this wrapper:
const generateClassName = createGenerateClassName({
disableGlobal: true,
});
return (
<StylesProvider generateClassName={generateClassName}>
<ThemeProvider theme={theme}>
{props.children}
</ThemeProvider>
</StylesProvider>
)
推荐阅读
- pandas - 是否可以将 Series.str.extract 与 Dask 一起使用?
- pagerduty - 如何通过警报名称设置警报严重性?
- rust - 怎么可能所有闭包都实现“FnOnce”?
- javascript - 在 nuxt vue/typescript 项目中包含 Vue 组件作为节点模块
- vue.js - 如何根据 vue.js 绑定使用 sass 使我的类名动态化?
- c# - Blazor WASM:List.Remove() 调用似乎正在删除对对象的所有引用
- c++ - istringstream 不工作它没有分隔我输入的数字
- excel - 根据前 N 个值有条件地标记每个组(2 列)的字段
- c# - 序列化没有键的匿名 JSON 数组
- c++ - 如果规则和解析器的属性类型不匹配,如何访问精神规则的属性?