前言:
在react中,我们有常用的有四种方式来显示元素的显示和隐藏,和vue不同,vue中我们使用v-if或v-show来显示元素的隐藏和显示
下面分别介绍一下在react中隐藏和显示元素的方法
第一种:用style来显示隐藏
import React, { useState } from 'react'
export default function Boke() {
const [isShow,setisShow] = useState(false)
const check = ()=>{
setisShow(!isShow)
}
return (
<div>
{/*第一种方式,用style来显示隐藏*/}
<button style={{display:isShow?'block':'none'}}>古力娜扎</button>
<button style={{display:isShow?'none':'block'}}>迪丽热巴</button>
<button onClick={()=>check()}>点击切换</button>
</div>
)
}
第二种:用三元运算符
import React, { useState } from 'react'
export default function Boke() {
const [isShow, setisShow] = useState(false)
const check = () => {
setisShow(!isShow)
}
return (
<div>
{/*第二种方法,用三元运算符*/}
{isShow ? <button >古力娜扎</button> : <button >迪丽热巴</button>}
<button onClick={() => check()}>点击切换</button>
</div>
)
}
第三种:通过短路逻辑进行元素显隐
import React, { useState } from 'react'
export default function Boke() {
const [isShow, setisShow] = useState(false)
const check = () => {
setisShow(!isShow)
}
return (
<div>
{/*第三种方式*/}
{isShow && <button >古力娜扎</button>}
{!isShow && <button >迪丽热巴</button>}
<button onClick={() => check()}>点击切换</button>
</div>
)
}