Material-ui:darkTheme不影响包裹的孩子

时间:2016-10-25 08:17:41

标签: reactjs themes components material-ui

我的问题非常简单,我想在我的应用程序的一部分中使用Material-ui默认的darkTheme。以下是代码示例:

<div>
  <MuiThemeProvider muiTheme={getMuiTheme(darkBaseTheme)}>
    <div>
      <AppBar title="I am dark" />
      <MyCustomComponent label="I should be dark but I am not" />
    </div>
  </MuiThemeProvider>
  <MuiThemeProvider muiTheme={getMuiTheme(lightBaseTheme)}>
      <p>I am in the lightBaseTheme (default theme)</p>
  </MuiThemeProvider>
</div>

应用程序的第一部分必须是黑暗的主题(这是一个左侧菜单),光明主题的第二部分(这是应用程序本身)。

AppBar的直接子项MuiThemeProvider确实是黑暗的,但MyCustomComponent及其子项(即使它们是基础Material-ui组件,如RaisedButton)也是不使用黑暗主题。

MyCustomComponents及其所有子子使用黑暗主题的最简单方法是什么?

2 个答案:

答案 0 :(得分:2)

您需要将MuiThemeProvider内的所有内容都包含在一个元素中。

<MuiThemeProvider muiTheme={getMuiTheme(darkBaseTheme)}> <div> <AppBar title="I am dark" /> <MyCustomComponent label="I should be dark but I am not" /> </div> </MuiThemeProvider>

实际上你必须有像

这样的错误

MuiThemeProvider.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.

当然,Material-UI中的MyCustomComponent个组件只有主题外观。您需要手动制作的所有其他内容:以Jeff McCloud显示的方式或使用此类上下文:

function MyCustomComponent (props, context) {
    const { palette } = context.muiTheme;
    // Now you have access to theme settings. for example: palette.canvasColor
}

MyCustomComponent.contextTypes = {
    muiTheme: React.PropTypes.object.isRequired,
};

另一种样式化纯HTML或React组件的方法是将它们包装起来 react-theme-provider。像这样:

import ThemeProvider from 'react-theme-provider';

<MuiThemeProvider muiTheme={getMuiTheme(darkBaseTheme)}>
  <div>
    <AppBar title="I am dark" />
    <ThemeProvider>
      <MyCustomComponent label="I should be dark and I am!" />
    </ThemeProvider>
  </div>
</MuiThemeProvider>

参考:https://github.com/callemall/material-ui/blob/master/src/styles/MuiThemeProvider.js#L7

答案 1 :(得分:1)

您需要指定您的自定义组件是&#34;可设置主题&#34;。您可以通过将组件包装在“muiThemeable”中来实现此目的。高阶分量:

import React from 'react';
import muiThemeable from 'material-ui/styles/muiThemeable';

class MyCustomComponent extends React.Component {
// ... your component will now have access to "this.props.muiTheme"
}


export default muiThemeable()(MyCustomComponent);

参考:http://www.material-ui.com/#/customization/themes