Method to stop switching between true/false when the value does not need to change
P粉957723124
P粉957723124 2023-08-14 19:43:19
0
1
481
<p>I have a simple true/false toggle function: </p> <pre class="brush:php;toolbar:false;">import {useState} from 'react' const [ isTrue, setIsTrue] = useState(true) function handleSwitcher(){ {isTrue ? setIsTrue(false) : setIsTrue(true)} } <button onClick={()=>{ handleSwitcher() console.log(isTrue) }}> set to true </button> <button onClick={()=>{ handleSwitcher() console.log(isTrue) }}> set to false </button></pre> <p>If we click on these two buttons, it will always present the opposite result of true or false. What I need is that if the value of isTrue is false and I click the "Set to False" button, it does not change the value of isTrue to true. Likewise, for the "Set to True" button, it should not change the value of isTrue to false when the value is true. </p>
P粉957723124
P粉957723124

reply all(1)
P粉165823783

You don't need a handleSwitcher, just set the desired value when the button is clicked and then it will do exactly what you want

import {useState} from 'react'
const [ isTrue, setIsTrue] = useState(true)

<button onClick={()=>{
    setIsTrue(true)
    console.log(isTrue)
}}>
   设置为true
</button>

<button onClick={()=>{
    setIsTrue(false)
    console.log(isTrue)
}}>
   设置为false
</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!