简体   繁体   English

三元运算符不适用于this.state react js

[英]ternary operator not working for this.state react js

Trying to change my header background color (for a start, eventually i will change more with the style. ) by a click. 尝试通过单击来更改我的标题背景颜色(首先,最终我将使用样式进行更多更改。)。

however it fails to work . 但是它无法工作。

toggleHeader(){
    var newState;
    newState = "headerBig" ? "headerSmall" : "headerBig";
    this.setState({
    toggleHeader: newState
})

} }

What i'm trying to change is my header className={this.state.toggleHeader} 我要更改的是我的标题className = {this.state.toggleHeader}

Am I not doing this right? 我不正确吗?

console log keeps returning "headerSmall" after it changes once. 一次更改后,控制台日志将继续返回“ headerSmall”。

Fixed 固定

I used this code to fix it... added a state of "isHeaderBig" and i am toggling that too. 我使用此代码对其进行了修复...添加了“ isHeaderBig”状态,我也将其切换。 seems like double the work,, but. 似乎是工作的两倍,但是。

toggleHeader(){ var newState = (this.state.isHeaderBig ? "headerSmall" : "headerBig"); this.setState({ toggleHeader: newState, isHeaderBig: !this.state.isHeaderBig }) }

toggleHeader(){
var newState;
newState = this.state.toggleHeader === "headerBig" ? "headerSmall" : "headerBig";
this.setState({
toggleHeader: newState

}) })

this is the right way, "headerBig" is always true 这是正确的方法,“ headerBig”始终为真

The correct way of writing the line with the ternary operator is: 用三元运算符编写行的正确方法是:

newState = newState === "headerBig" ? "headerSmall" : "headerBig";

Notice the comparison on the left of ? 请注意左侧的比较? .

Otherwise, just "headerBig" will always evaluate to true and the ternary operator will always return "headerSmall" . 否则,仅"headerBig"将始终求值为true ,三元运算符将始终返回"headerSmall" This is the first problem. 这是第一个问题。

The second one is you have to keep newState outside the function, or it will loose the state between clicks. 第二个问题是您必须将newState保留在函数之外 ,否则它将使两次单击之间的状态失去作用。

This is a working example: 这是一个工作示例:

 var newState = "headerBig"; // outside the handler $("#headertest").on("click", () => { newState = newState === "headerBig" ? "headerSmall" : "headerBig"; // with condition $("#headertest").text(newState); }); $("#headertest").text(newState); // initialize 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="headertest"></div> 

newState = "headerBig" ? "headerSmall" : "headerBig";

Is basically the same as 基本上和

if ("headerBig") {
    newState = "headerSmall"
} else {
    newState = "headerBig"
} 

Do you see what the problem is? 您知道问题出在哪里吗? "headerBig" is truthy, so the first case will ways run. "headerBig"是真实的,因此第一种情况将运行。

Perhaps you meant something like: 也许您的意思是:

newState = oldState === "headerBig" ? "headerSmall" : "headerBig";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM