Material-ui withTheme()给出错误" TypeError:Object(...)不是函数"

时间:2018-03-10 04:26:50

标签: reactjs material-ui create-react-app

编辑:我安装了v1.0.0.36测试版,并从该版本的docs(看起来与我相同)中复制了样本,并且它可以直接使用。不知道问题是什么,但感谢回复

我正在尝试使用Material-UI withTheme来访问组件中的主题。

我已经跟踪docs中的示例,该示例通过create-react-app packager确定,但在浏览器中给出了错误:TypeError:Object(...)不是函数 并突出显示代码行> 17 | export default withTheme()(WithTheme);

我已将示例代码缩减为withTheme()的最基本用法,但仍然收到此错误

withtheme.js

import React from 'react';
import { withTheme } from 'material-ui/styles';

function WithTheme() {

    const styles = {
        primaryText: {
            color: 'red',
        }
    };

    return (
        <h1 style={styles.primaryText}>Hello</h1>
    );
}

export default withTheme()(WithTheme);

编辑:为了帮助澄清问题,这里是App.js文件。

import React, { Component } from 'react';
import './App.css';
import 'typeface-roboto';

import AppBar from 'material-ui/AppBar';

import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import {brown500, brown900} from 'material-ui/styles/colors';
import getMuiTheme from 'material-ui/styles/getMuiTheme';

import WithTheme from './components/withtheme';

const Theme = getMuiTheme({
  palette: {
    primary1Color: brown900,
    primary2Color: brown500,
  }
});

class App extends Component {
  render() {
    return (
      <MuiThemeProvider muiTheme={Theme} >
          <AppBar
            title="Title"
            iconClassNameRight="muidocs-icon-navigation-expand-more" />
          <WithTheme />
      </MuiThemeProvider>
    );
  }
}

export default App;

我已使用muiThemeProvider自定义主题并将primary1Color更改为棕色。当我从App.js中删除WithTheme组件时,这一切都正常 - AppBar是预期的棕色。问题是当我尝试使用mui withTheme函数时出现错误。

我的目的是将WithTheme组件中的h2设置为当前主题对primary1Color

的所有颜色

**结束编辑

任何帮助将不胜感激。很高兴发布doco示例代码的(几乎)精确副本,如果需要,可以实现相同的错误。

由于

4 个答案:

答案 0 :(得分:2)

由于MaterialUI不再处于Beta版中,因此规范有所更改,已经超出了Liam的答案。根据{{​​3}}

import { withTheme } from '@material-ui/core/styles';
export default withTheme()(WithTheme);

答案 1 :(得分:1)

除非您想为组件制作特定样式

,否则无需使用withStyles()

使用MuiThemeProvider扭曲您的应用,然后您就可以正确使用主题

Material-Ui 0.20.0

对于访问主题颜色,请使用getMuiTheme

import getMuiTheme from 'material-ui/styles/getMuiTheme';
export default muiThemeable()(App)

http://www.material-ui.com/#/components/app-bar

Working Demo

Material-Ui 1.0.0 beta

对于访问主题颜色,请使用withTheme

import { withTheme } from 'material-ui/styles';
export default withTheme()(App)

https://material-ui-next.com/demos/app-bar/

Working Demo V1

答案 2 :(得分:0)

如果您打算更改material-ui的主题,我更喜欢使用getMuiTheme。有关文档,请参阅http://www.material-ui.com/#/customization/themes。这里发生的是,您使用JavaScript为您的组件设置样式,因此导出需要调用withStyles。

导出默认withStyles(样式)(WithTheme);

答案 3 :(得分:0)

从材料4开始,规范再次进行了更改:https://material-ui.com/styles/api/#withtheme-component-component(因此也超过了Awnage的回答)。

现在是:

import { withTheme } from '@material-ui/styles';

export default withTheme(MyComponent);