材质 UI 按钮导致无效的钩子调用

时间:2021-06-19 22:00:46

标签: reactjs create-react-app

我是 React 应用程序的初学者,我刚刚完成了应用程序的设置并想使用 material UI for buttons

这是我的代码。

import Button from '@material-ui/core/Button';
import React from 'react';
import logo from './logo.svg';
import './App.css';


function App() {
  return (
    <div className = "App">
      <header className='App-header'>
        <Button>Click here</Button>
        <img src={logo} className="App-logo" alt="logo" />
      </header>
    </div>
  );
}

export default App;

我运行它,它给了我 Error: Invalid hook call. Hooks can only be called inside of the body of a function component. 并且错误指向:

   4 | import App from './App';
   5 | import reportWebVitals from './reportWebVitals';
   6 | 
>  7 | ReactDOM.render(
   8 |   <React.StrictMode>
   9 |     <App />
  10 |   </React.StrictMode>,

这是我的 package.json 以防万一,但我认为那里没有任何问题。

{
  "name": "schedule",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "4.0.3",
    "web-vitals": "^1.1.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

我花了很多时间试图解决这个问题,请帮忙

2 个答案:

答案 0 :(得分:0)

我在这个例子中复制了你的代码

<块引用>

https://codesandbox.io/embed/dreamy-euler-jhu8t?fontsize=14&hidenavigation=1&theme=dark

只需要安装材料ui

// with npm
npm install @material-ui/core

// with yarn
yarn add @material-ui/core

如果不需要就删除

<块引用>

来自'./reportWebVitals'

答案 1 :(得分:0)

我只需要在终端中执行 npm install @material-ui/core。它之前不在依赖项列表中。感谢@Claire Lin。