首页 > 解决方案 > 组件样式是否可以限定范围而不是内联以防止同一页面上的多个 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 为每个组件导出的样式专门针对该组件,以便样式不会相互覆盖?

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

推荐阅读