简体   繁体   English

如何在JSX中使用If-Else

[英]How to use If-Else in JSX

I understand how to use it in simple situations: 我理解如何在简单的情况下使用它:

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

But how to use it for big DOM? 但是如何将它用于大型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? 怎么做正确?

You can't do that. 你不能这样做。 I see two potential problems from what you've provided. 我从你提供的内容中看到了两个潜在的问题。 First, you can only return one DOM node. 首先,您只能返回一个DOM节点。 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-else的方法可以通过使用这里建议的IIFE来完成: 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 components 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: 好的,对于大型DOM,就像这样:

{() => {
  { 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 顺便说一句,我创建了一个小型库来做一个lisp风格 - 如果 - 其他

import { _if } from 'jsxcond';

...

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

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

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