【问题标题】:Material-UI React: Global theme override for Paper componentMaterial-UI React:Paper 组件的全局主题覆盖
【发布时间】:2019-05-23 05:17:04
【问题描述】:

我有一个使用最新的 Material-UI 组件库构建的 React 应用。

我使用了Paper 组件的许多实例。我想一次对所有它们应用边距和填充,而无需为每个实例手动重复此过程。

我查找了有关该主题的Material-UI documentation,据我所知,以下代码应该正确覆盖 Paper 的外观:

const theme = createMuiTheme({
    overrides: {
        Paper: {
            root: {
                padding: '10px',
                marginBottom: '10px',
            },
        },
    },
});

下面是覆盖样式应该应用的地方:

<ThemeProvider theme={theme}>
    {/* ... */}
    <Paper>
        Content goes here
    </Paper>
    {/* ... */}
</ThemeProvider>

但未应用覆盖的值。关于发生了什么的任何建议?

谢谢!

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:

    在您的 App.js 中添加(请注意 MuiPaper 而不是 Paper):

    const theme = createMuiTheme({
      overrides: {
        MuiPaper: {
          root: {
            padding: '10px',
            marginBottom: '10px'
          },
        },
      }
    });
    

    在同一个 App.js 文件中,包装您的 HTML:

    class App extends Component {
      render() {
        return (
          <MuiThemeProvider theme={theme}>
            <div className="App">
              <YourComponent1 />      
              <YourComponent2 />
              ...
            </div>
          </MuiThemeProvider>
        );
      }
    }
    

    这样,任何由 React 渲染的 Paper 组件都会有你的 CSS。

    顺便说一句,我创建了 MUI schematics 模块,它添加了 Material UI 支持,自动生成了几个 Material UI 组件,并在 App.js 中添加了通用主题规则。欢迎您来看看/尝试一下...

    【讨论】:

      【解决方案2】:

      我发现了问题。

      用于 CSS 的内部组件名称是 MuiPaper,而不仅仅是 Paper。以下产生了预期的结果:

      overrides: {
          MuiPaper: {
              root: {
                  padding: '10px',
                  marginBottom: '10px',
              },
          },
      },
      

      【讨论】:

        【解决方案3】:

        如果您已经将 CssBaseline 组件用于全局重置,您也可以使用它...这一切都取决于您如何构建主题。

        以下示例来自 Mui 文档:

        const theme = createMuiTheme({
          overrides: {
            MuiCssBaseline: {
              '@global': {
                html: {
                  WebkitFontSmoothing: 'auto',
                },
              },
            },
          },
        });
              
        
         // ...
        return (
          <ThemeProvider theme={theme}>
            <CssBaseline />
            {children}
          </ThemeProvider>
        );
        

        您可以从此处的文档中获取更多详细信息 using CssBaseline to inject global theme overrides.

        【讨论】:

          猜你喜欢
          • 2019-05-21
          • 2021-12-19
          • 2021-07-06
          • 2019-03-14
          • 1970-01-01
          • 1970-01-01
          • 2022-06-15
          • 2020-04-14
          • 1970-01-01
          相关资源
          最近更新 更多