ternary operator in jsx to include html with react

前端 未结 6 1811
离开以前
离开以前 2020-12-23 11:12

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

6条回答
  •  攒了一身酷
    2020-12-23 11:59

    The syntax for ternary is condition ? if : else. To be safe, you can always wrap the entire ternary statement inside parenthesis. JSX elements are also wrapped in parenthesis. The fat arrow in an arrow function is always preceeded by two parenthesis (for the arguments) - but you don't need any functions here anyway. So given all of that, there are a couple of syntax errors in your code. Here's a working solution:

    render() {
      return (this.state.message === 'failed' ? (
       
    Something went wrong
    ) : null); }

    Edit: if this is inside other markup, then you don't need to call render again. You can just use curly braces for interpolation.

    render() {
      return (
        
    {this.state.message === 'failed' ? (
    Something went wrong
    ) : null}
    ); }

提交回复
热议问题