簡體   English   中英

將鈎子反應到組件中的工具類

[英]React hooks to toogle class in component

我知道過去有人問過類似的問題,但我認為他們都沒有達到目標。 大多數都基於類組件,與我想要做的並不完全相同。 所以我有兩個組件要通過 onClick 打開和關閉。

      <div
        className={`${showInfo === false ? "carousel_wrapper" : "no_display"}`}
      ></div>

      {/* <!-- page info below --> */}

      <div
        className={`${showInfo === true ? "page_info_content" : "no_display"}`}
      >

默認情況下,我將 var 設置為 true:

var showInfo = true;

現在我試圖通過點擊來切換課程。 我知道為了讓它在函數組件中工作,我需要 useState 因為這是 React 觀察元素變化的方式。 但是我可以使用“useState”來更改默認值嗎? 像這樣:

let toggleInfo = () => {
  const [infTrue, infoFalse] = useState(true);
  showInfo = infoFalse(false);
  return showInfo; 
  };

我收到一個錯誤:

Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

或者這根本沒有意義? 請注意,我對 React 和 JS 總體上還是很陌生,所以我可能會從一個奇怪的角度看待這個問題,但 JS E6+ 有一個簡單的切換選項似乎很奇怪,但像 React 這樣的高級工具需要更復雜的方法。 我相信這種感覺會隨着時間而改變。 歡迎大家提出意見。

您必須在函數 toggleInfo 之外聲明狀態變量。

你的功能組件應該是這樣的

const funcComp = ()=>{
  const [infTrue, infoFalse] = useState(true);
  const toggleInfo = () => {
       infoFalse(false);
       }
  return(
   <>
   <button onClick={toggleInfo}>Click to toggle </button>
     <div
        className={`${showInfo === false ? "carousel_wrapper" : "no_display"}`}
      ></div>

      {/* <!-- page info below --> */}

      <div
        className={`${showInfo === true ? "page_info_content" : "no_display"}`}
      >
    </>
 )

}

歡迎使用 React 和 JS。 祝你好運 :)

React hooks 必須是組件的根級別。 它不可能在其他任何東西里面。 聲明狀態后,您可以使用數組索引 1 中聲明的方法更改它:

const MyComponent = () => {
 const [state, setState] = useState(false)
 
 return <button onClick={() => setState(true)} >Click Me</button>
}

每次狀態改變時,組件都會重新渲染。

在函數體中定義狀態。 鈎子的規則說它們只能從功能組件主體或其他鈎子中調用。 useState鈎子返回一個狀態數組和狀態更新函數,即const [state, setState] = useState(); .

const [infoTrue, setInfoTrue] = useState(true);

然后使用下一個值在回調中調用狀態更新程序,即false

const toggleInfo = () => setInfoTrue(false);

定課。 由於infoTrue是一個布爾值,因此請使用它的真/假對您有利,即不要直接與truefalse進行比較。 此外,字符串模板是不必要的,只需有條件地返回類名字符串。

<div
  className={infoTrue ? "page_info_content" : "no_display"}
>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM