无效的挂接调用.当使用material-ui将样式应用于类基础组件时,只能在函数组件的主体内部调用钩子 [英] Invalid hook call. Hooks can only be called inside of the body of a function component when apply style to class base component with material-ui

查看:49
本文介绍了无效的挂接调用.当使用material-ui将样式应用于类基础组件时,只能在函数组件的主体内部调用钩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始使用material-ui学习reactjs,但是在将样式应用于我的组件时遇到此错误.我的代码:

I am just started to learn reactjs using material-ui but getting this error when apply style to my component. My code:

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;

这是错误:

推荐答案

material-ui makeStyles 函数仅在函数组件内部起作用,因为它在内部使用了新的React Hooks API.

material-ui makeStyles function only works inside function components, as it uses the new React Hooks APIs inside.

您有两个选择:

  1. 将您的类组件转换为功能组件.
  2. 像在Material-ui文档中一样,使用高阶组件

我个人推荐第一种方法,因为这已成为React开发中的新标准.本教程可以帮助您开始使用功能组件检查文档中是否有React Hooks

I personally recommend the first approach, as this is becoming the new standard in React development. This tutorial may help you get started with functional components and check the docs for React Hooks

这篇关于无效的挂接调用.当使用material-ui将样式应用于类基础组件时,只能在函数组件的主体内部调用钩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆