admin管理员组

文章数量:1387310

I understand how to use it in simple situations:

{(this.state.show) ? <span>Show</span> : null}

But how to use it for big DOM?

{ if (this.state.show) {
  <span className={this.state.className}>Hi</span>
  {this.state.text}
} else {
  {this.state.text}
}
}

Of course, it doesn't work. How to do it correctly?

I understand how to use it in simple situations:

{(this.state.show) ? <span>Show</span> : null}

But how to use it for big DOM?

{ if (this.state.show) {
  <span className={this.state.className}>Hi</span>
  {this.state.text}
} else {
  {this.state.text}
}
}

Of course, it doesn't work. How to do it correctly?

Share Improve this question edited Jan 30, 2016 at 18:13 Dmitry Shvedov 3,3164 gold badges40 silver badges56 bronze badges asked Feb 6, 2015 at 0:51 Nick BolshNick Bolsh 1501 gold badge3 silver badges15 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

You can't do that. I see two potential problems from what you've provided. First, you can only return one DOM node. Second, (and this might be because it's not your full code), your braces are not syntactically correct. Without knowing your full source code, you can try something like:

render: function() {
    var header;

    if (this.state.show) {
        header = <span className={ this.state.className }>Hi</span>;
    }
    return <div>
               { header }
               { this.state.text }
           </div>
}

Another way of doing if-else can be done by use of an IIFE as suggested here: https://facebook.github.io/react/tips/if-else-in-JSX.html.

{(() => {
  if (this.state.show) {
    <span className={this.state.className}>Hi</span>
    {this.state.text}
  } else {
    {this.state.text}
  }
})()}

Firstly you cannot use multiple ponents in one statement. You must do like this:

if (this.state.show) {
  <span>
    <span className={this.state.className}>Hi</span>
    {this.state.text}
  </span>
} else {
  {this.state.text}
}

Ok, for big DOM, just like this:

{() => {
  { if (this.state.show) {
    <span>
      <span className={this.state.className}>Hi</span>
      {this.state.text}
    </span>
    } else {
      {this.state.text}
    }
}}

or

{ this.state.show ? (
    <span>
      <span className={this.state.className}>Hi</span>
      {this.state.text}
    </span>
  ) : (
    {this.state.text}
  )
}

BTW, I have created a small library to do a lisp style if - else

import { _if } from 'jsxcond';

...

{ _if( this.state.show, 
    () => (
      <span>
        <span className={this.state.className}>Hi</span>
        {this.state.text}
      </span>
    ), 
    this.state.text
  )
}
...

本文标签: javascriptHow to use IfElse in JSXStack Overflow