Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
129 views
in Technique[技术] by (71.8m points)

javascript - ternary operator in jsx to include html with react

I'm using react and I'm trying to display this error message if this.state.message === 'failed'. But I'm really not sure why this ternary operation isn't working. What am I doing wrong here?

render() {
    ...
    <div className="row">
        return (this.state.message === 'failed') ? ( =>{" "}
        {
            <div className="alert alert-danger" role="alert">
                Something went wrong
            </div>
        }
        )() : false; }
    </div>
}

Right now its just displaying return (this.state.message === 'failed') ? ( => in the html

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I currently like to format my ternaries like this in react:

render () {
  return (
    <div className="row">
      { //Check if message failed
        (this.state.message === 'failed')
          ? <div> Something went wrong </div> 
          : <div> Everything in the world is fine </div> 
      }
    </div>
  );
}

You are correct that IIFEs can be used within a render statement as well as ternary expressions. Using a normal if .. else statement is valid, but the render function's return statement can only contain expressions so you would have to do those elsewhere..


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...