简体   繁体   中英

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}

Am I not doing this right?

console log keeps returning "headerSmall" after it changes once.

Fixed

I used this code to fix it... added a state of "isHeaderBig" and i am toggling that too. 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

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" . 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.

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.

Perhaps you meant something like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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