[英]toogle component on click with react hooks
I'm toggling a component while clicking on div.我在点击 div 时切换了一个组件。 It toogle down when clicked but does not close when clicked again what am i doing wrong?
单击时它会向下移动,但再次单击时不会关闭我做错了什么?
export default function Shiva() {
const [loan, setLoan] = useState(false);
const handleClick = () => {
setLoan(true);
}
return (
<div className="">
<div className="">
<div className="loan-type-select" onClick={handleClick}>
<div className="">
<img src="" />
</div>
<p>SBA 7A Loan</p>
{loan ? <Data /> : '' }
</div>
</div>
</div>
Look closely at your click handler:仔细查看您的点击处理程序:
const handleClick = () => {
setLoan(true);
}
Regardless of the current state of loan
, it will always set the new state of loan
to true
.无论当前的
loan
state 是什么,它都会始终将loan
的新 state 设置为true
。
If you want to close it when it's open, toggle the current state instead of passing true
.如果您想在它打开时将其关闭,请切换当前的 state 而不是传递
true
。
const handleClick = () => {
setLoan(!loan);
}
I would like to add that instead of using:我想添加它而不是使用:
setLoan(!loan)
It is better to use:最好使用:
setLoan((preValue)=>{!preValue})
This way you make sure you won't face any issues (you are changing the previous value instead of changing the actual value).这样可以确保您不会遇到任何问题(您正在更改以前的值而不是更改实际值)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.