React onClick doest work correctly on if conditional

huangapple go评论55阅读模式
英文:

React onClick doest work correctly on if conditional

问题

I have a problem with React.

I wrote a function:

function click(event) {
    let element = event.currentTarget.querySelector(".infos__content");
    if (element.style.display) {
        alert("test")
        element.style.display = "none";
    }
    else {
        alert("test1")
        element.style.display = "block";
    }
}

and i called this function successfully in a DIV Container on the "onClick" attribute but it works for just one time, when i click on my div Container again, my if conditional always is true, does anyone know why?

I have google it already but cant find a solution for this

英文:

I have a problem with React.

I wrote a function:

   function click(event) {
    let element = event.currentTarget.querySelector(".infos__content");
    if (element.style.display) {
        alert("test")
        element.style.display = "none";
    }
    else {
        alert("test1")
        element.style.display = "block";
    }
}

and i called this function successfully in a DIV Container on the "onClick" attribute but it works for just one time, when i click on my div Container again, my if conditional always is true, does anyone know why?

I have google it already but cant find a solution for this

答案1

得分: 2

当您首次检查element时,它将是''。这将计算为false。

element.style.display
''

然后当您分配'none'时,它将是'none'。

element.style.display='none'
'none'

element.style.display
'none'

'none'是一个真字符串值,因此表达式始终为true。要使您的评估为false,必须分配''或null

英文:

When you are first checking element it will be ''. This will evaluate to false.

element.style.display
''

Then when you assign 'none', it will be 'none'.

element.style.display='none'
'none'

element.style.display
'none'

'none' is a true string value so the expression will always be true. To make your evaluation false you must assign '' or null.

答案2

得分: 2

你还可以在你的函数内部使用if语句来检查元素的当前样式状态,然后相应地进行更改。

function click(event) {
    let element = event.currentTarget.querySelector(".infos__content");
    if (element.style.display === "block") {
        alert("test");
        element.style.display = "none";
    }
    else {
        alert("test1");
        element.style.display = "block";
    }
}
英文:

You can also use If statement inside your function to check the current style state of your element and then change accordingly.

function click(event) {
    let element = event.currentTarget.querySelector(".infos__content");
    if (element.style.display === "block") {
        alert("test")
        element.style.display = "none";
    }
    else {
        alert("test1")
        element.style.display = "block";
    }
}

huangapple
  • 本文由 发表于 2023年5月15日 12:45:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76250934.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定