How to use ReactJS to hide elements
P粉136356287
P粉136356287 2023-09-07 19:21:22
0
2
478

I want to show a text on the screen and only hide it when a button is pressed, but I don't know how to do it. I want to use useState to achieve this effect:

const [textVisibility, setTextVisibility] = useState(true)
<button onClick={() => setTextVisibility(false)} />

The problem I found is that when the button is clicked, the page will re-render and the visibility value will change to the default value (true). what should I do?

P粉136356287
P粉136356287

reply all(2)
P粉579008412

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>
  );
}
P粉155128211
const App(){
    
    const [isVisible, setIsVisible] = useState(false)
    
    return (
            <>
            {isVisible ? <label> 点击按钮后将显示此文本 </label> : null 
   }
            <button onClick={()=>setIsVisible(true)}>点击显示</button>
          
         </>
    )
    
    }
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!