![](/img/trans.png)
[英]Trying to Create a react Component but getting React Hook "React.useState" cannot be called at the top level."
[英]React Hook "React.useState" cannot be called in a class component
在 ReactJS 中,我嘗試將 div class 名稱切換到另一個元素。 但我收到這樣的錯誤消息。 無法在 class 組件中調用 React Hook “React.useState”
我需要什么來修復代碼?
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;
您不能在 class 組件內使用 Hook,但您絕對可以在單個樹中將類和 function 組件與 Hook 混合使用。 ... 從長遠來看,我們希望 Hooks 成為人們編寫 React 組件的主要方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.