我正在尝试使用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示例代码的(几乎)精确副本,如果需要,可以实现相同的错误。
由于
答案 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
Material-Ui 1.0.0 beta
对于访问主题颜色,请使用withTheme
import { withTheme } from 'material-ui/styles';
export default withTheme()(App)
答案 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);