[英]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 组件的主要方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.