【问题标题】:React - Material-UI - Typescript: makeStyles hook gives Invalid Hook Call inside a function componentReact - Material-UI - Typescript:makeStyles 钩子在函数组件内给出了无效的钩子调用
【发布时间】:2021-06-12 04:55:41
【问题描述】:

我真的不明白我做错了什么。

我正在使用 (javascript) 文档中描述的 makeStyles 钩子,我得到了这个 Invalid Hook Call。我正在使用 TypeScript 4.1.2、React 17.0.1 和 React Types 17.0.0。

这是组件代码:

import React from 'react';
import { Theme, makeStyles } from '@material-ui/core/styles';

interface Props
{
    isVisible: boolean;
}

const useStyles = makeStyles( ( theme: Theme ) => ( {
    root: {
        background: 'red',
        height: 100,
    },
} ) );

const Nav: React.FC<Props> = ( props: Props ) =>
{
    const { isVisible } = props;

    const classes = useStyles( {} );

    return (
       <div className={classes.root}>

       </div>
    );
};

export default Nav;

【问题讨论】:

  • 很奇怪。我试图在我的 React 项目中运行你的 useStyle 钩子并且它正在工作。我不使用ts。你能提供更多关于错误的信息吗?
  • 我马上添加。
  • 看起来 TS 只是弄乱了你的 material-ui makeStyles 钩子。女巫很奇怪。因为我只是像使用 .jsx 文件而不是 .tsx 文件一样调用钩子
  • @AndreyRF,你怎么看?你以前遇到过这种情况吗?

标签: reactjs typescript material-ui makestyles


【解决方案1】:

答案比我想象的要简单。似乎使用"react-scripts":"4.0.3",代码有效。我不记得我以前使用的是哪个版本的cra(我在检查之前更新了它),但最新版本看起来可以工作。

这是我所做的:

  1. 我在我的 git 中创建了一个新分支。
  2. 我完全删除了应用程序
  3. 我在终端输入了npm i -g create-react-app
  4. 我创建了一个新的 React 应用程序:create-react-app &lt;your file&gt; --template typescript
  5. 最后我添加了依赖和库:npm i @material-ui/core @material-ui/icons @material-ui/lab &lt;other-libraries-here&gt; ... @types/material-ui &lt;other-types-here&gt; ...
  6. 我像以前一样更改了 tsconfig.json 文件,正如 material-ui documentation 所建议的那样(我将 strictNullChecks 保留为 false 作为个人喜好)
  7. 我使用npm/yarn start 运行了启动脚本。

我希望这个答案可以帮助遇到这个问题的人!快乐的黑客攻击!

【讨论】:

    猜你喜欢
    • 2021-09-10
    • 2022-01-24
    • 2021-08-04
    • 2020-02-14
    • 2023-02-11
    • 2020-02-14
    • 2019-12-06
    • 2021-03-23
    • 1970-01-01
    相关资源
    最近更新 更多