简体   繁体   中英

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

In ReactJS, I tried toggle div class name to another element. But I got error message like this. React Hook "React.useState" cannot be called in a class component

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. ... In the longer term, we expect Hooks to be the primary way people write React components.

React Hooks FAQ

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM