Reactjs 无效的钩子调用。当使用材质ui将样式应用于类基组件时,只能在函数组件主体内部调用挂钩
我刚开始学习使用MaterialUI的reactjs,但在将样式应用到组件时出现了这个错误。我的代码:Reactjs 无效的钩子调用。当使用材质ui将样式应用于类基组件时,只能在函数组件主体内部调用挂钩,reactjs,material-ui,Reactjs,Material Ui,我刚开始学习使用MaterialUI的reactjs,但在将样式应用到组件时出现了这个错误。我的代码: const useStyles = makeStyles(theme => ({ root: { flexGrow: 1, }, menuButton: { marginRight: theme.spacing(2), }, title: { flexGrow: 1, }, })); cla
const useStyles = makeStyles(theme => ({
root: {
flexGrow: 1,
},
menuButton: {
marginRight: theme.spacing(2),
},
title: {
flexGrow: 1,
},
}));
class NavMenu extends React.Component {
constructor(props) {
super(props);
this.state = {
isOpen: false
};
}
render() {
const classes = useStyles();
return (
<div className={classes.root}>
<AppBar position="static">
<Toolbar>
<IconButton
edge="start"
className={classes.menuButton}
color="inherit"
aria-label="Menu"
>
<MenuIcon />
</IconButton>
<Typography
variant="h6"
className={classes.title}
>
News
</Typography>
<Button color="inherit">Login</Button>
</Toolbar>
</AppBar>
</div>
);
}
}
export default NavMenu;
const useStyles=makeStyles(主题=>({
根目录:{
flexGrow:1,
},
菜单按钮:{
边缘光:主题。间距(2),
},
标题:{
flexGrow:1,
},
}));
类NavMenu扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
伊索彭:错
};
}
render(){
const classes=useStyles();
返回(
新闻
登录
);
}
}
导出默认导航菜单;
这是一个错误:
材质ui
makeStyles
函数仅在函数组件内部工作,因为它在内部使用了新的API
您有两个选择:
和如果您创建了一个功能组件,但仍然遇到此问题。。。接下来要查找的是依赖项版本 我尝试了一个新的方法来测试一个MaterialUI组件,但出现了这个错误。我的依赖关系是: 反应16.12 反应dom 16.12 @材料界面/核心4.9.14 所以我不得不使用
react@latest
和反应-dom@latest
这让我想到了以下几点:
反应16.13.1
反应dom 16.13.1
@材料界面/核心4.9.14
在这里分享,这样它可以帮助其他人谁遇到这个。。。感谢您的提示将
与样式一起使用
:
App.js
:
import React, {Component} from 'react'
import App from './App'
import {ThemeProvider} from '@material-ui/styles'
import theme from '../theme'
export default class Root extends Component {
render() {
return (
<ThemeProvider theme={theme}>
<App/>
</ThemeProvider>
)
}
}
从'@material ui/core/styles'导入{withStyles}
// ...
常量样式=主题=>({
论文:{
填充:主题。间距(2),
// ...
},
// ...
})
类应用程序扩展了React.Component{
render(){
const{classes}=this.props
// ...
}
}
导出默认样式(样式)(应用程序)
Root.js
:
import React, {Component} from 'react'
import App from './App'
import {ThemeProvider} from '@material-ui/styles'
import theme from '../theme'
export default class Root extends Component {
render() {
return (
<ThemeProvider theme={theme}>
<App/>
</ThemeProvider>
)
}
}
看
请参阅。使用
和样式
替代,然后类
作为道具
出现。它起作用了。非常感谢。但是现在我不能使用“marginRight:theme.spathing(2)”。有没有在类中使用makeStyles?如果我需要在对象中保持状态呢?材质ui文档在任何地方都使用此功能构建。另一个选择是将类内容转换为简单的CSS,这虽然繁琐,但却是安全的。使用useState
将状态保存在函数组件中是一个不错的选择!