简体   繁体   English

无法在 class 组件中调用 React Hook “React.useState”

[英]React Hook "React.useState" cannot be called in a class component

In ReactJS, I tried toggle div class name to another element.在 ReactJS 中,我尝试将 div class 名称切换到另一个元素。 But I got error message like this.但我收到这样的错误消息。 React Hook "React.useState" cannot be called in a class component无法在 class 组件中调用 React Hook “React.useState”

What do I need to fix the code?我需要什么来修复代码?

import React from 'react';
 
class About extends React.Component{ 
  render(){
    const [show, setShow] = React.useState();
    return (
      <>
        <h1>About</h1>  
        <button className="toggle" onClick={() => setShow(!show)}>
          Toggle
        </button>
        <nav className={`nav ${show ? "show" : ""}`}>Navigation menu</nav>
      </>
    )
  }
}
  
export default About;

You can't use Hooks inside of a class component, but you can definitely mix classes and function components with Hooks in a single tree.您不能在 class 组件内使用 Hook,但您绝对可以在单个树中将类和 function 组件与 Hook 混合使用。 ... In the longer term, we expect Hooks to be the primary way people write React components. ... 从长远来看,我们希望 Hooks 成为人们编写 React 组件的主要方式。

React Hooks FAQ React Hooks 常见问题解答

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 试图创建一个反应组件,但无法在顶层调用 React Hook “React.useState”。” - Trying to Create a react Component but getting React Hook "React.useState" cannot be called at the top level." React Hook "React.useState" 在 function "form" 中调用,它既不是 React function 组件也不是自定义 React Hook ZC1C425268E68385D1AB5074C17A94F - React Hook "React.useState" is called in function "form" that is neither a React function component nor a custom React Hook function 错误“无法在 class 组件中调用 React Hook "useState"”的解决方案是什么 - What is the solution to the error 'React Hook "useState" cannot be called in a class component' React Hook“useState”无法在 class 组件中调用。 React Hooks 必须在 React function 组件或自定义 React Hook function 中调用 - React Hook "useState" cannot be called in a class component. React Hooks must be called in a React function component or a custom React Hook function 无法在 class 组件中调用 React Hook “useContext” - React Hook “useContext” cannot be called in a class component 无法在 class 组件中调用 React Hook“useTranslation” - React Hook "useTranslation" cannot be called in a class component React.useState() 的问题 - Troubles with React.useState() 无法在顶层调用 React Hook“useState”。 React Hooks 必须在 React function 组件或自定义 React Hook function 中调用 - React Hook "useState" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function Material-UI - 在 DataTable 中获取数据显示 =&gt; “React.useState” 不能在回调中调用 - Material-UI - fetching data display in DataTable => “React.useState” cannot be called inside a callback 不能在回调中调用 React Hook “useState” - React Hook “useState” cannot be called inside a callback
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM