gpt4 book ai didi

javascript - React Hook "useStyles"在既不是 React 函数组件也不是自定义 React Hook 函数的函数中被调用

转载 作者:行者123 更新时间:2023-12-05 08:14:04 25 4
gpt4 key购买 nike

根据标题,我在使用 React 实现 Material UI 时收到以下错误消息。

React Hook "useStyles" is called in function "appBar" which is neither a React function component or a custom React Hook function

我已经查看了钩子(Hook)的规则 ( https://reactjs.org/docs/hooks-rules.html ),但我不确定我错过了什么。如有任何帮助,我们将不胜感激。

这是我的源代码:

import React from 'react';
import { createStyles, makeStyles, Theme } from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import IconButton from '@material-ui/core/IconButton';
import MenuIcon from '@material-ui/icons/Menu';

const useStyles = makeStyles((theme: Theme) =>
createStyles({
root: {
flexGrow: 1,
},
menuButton: {
marginRight: theme.spacing(2),
},
title: {
flexGrow: 1,
},
}),
);

export default function appBar() {
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>
);
}

最佳答案

尝试使用 PascalCase 重命名您的组件.

eslint-plugin-react-hooks认为您的功能组件不是功能组件,因为它不是以大写字母开头。

注:react docs声明用户定义的组件在 JSX 中使用之前必须大写以避免被视为 HTML 元素。

在下面的示例中,我将组件命名为 AppBarWrapper,因为名称 AppBar 已被从 @material-ui/core 导入的组件使用/AppBar.

import React from 'react';
import { createStyles, makeStyles, Theme } from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import IconButton from '@material-ui/core/IconButton';
import MenuIcon from '@material-ui/icons/Menu';

const useStyles = makeStyles((theme: Theme) =>
createStyles({
root: {
flexGrow: 1,
},
menuButton: {
marginRight: theme.spacing(2),
},
title: {
flexGrow: 1,
},
}),
);

export default function AppBarWrapper() {
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>
);
}

关于javascript - React Hook "useStyles"在既不是 React 函数组件也不是自定义 React Hook 函数的函数中被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60795368/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com