我想在螢幕上顯示一段文本,並且只有在按下按鈕時才隱藏,但我不知道如何做。我想使用useState來實現這個效果:
const [textVisibility, setTextVisibility] = useState(true) <button onClick={() => setTextVisibility(false)} />
我發現的問題是,當點擊按鈕時,頁面會重新渲染,可見性的值將會變成預設值(true)。我該怎麼做?
P粉5790084122023-09-08 10:05:34
Idk what are you experiencing but for me it works fine the following code:
import React from 'react'; import {useState} from 'react'; export function App(props) { const [textVisibility, setTextVisibility] = useState(true) return ( <div className='App'> {textVisibility && <h1 onClick={() => setTextVisibility(!textVisibility)}>Hello React.</h1>} <button onClick={() => setTextVisibility(false)}>Invisible</button> <button onClick={() => setTextVisibility(true)}>Visible</button> </div> ); }