2015-02-06 47 views
4

我知道如何在簡單情況下使用它:如何使用的if-else在JSX

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

但如何使用它的大DOM?

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

當然,它不起作用。如何正確地做到這一點?

回答

5

你不能那樣做。我看到您提供的兩個潛在問題。首先,你只能返回一個DOM節點。其次,(這可能是因爲它不是你的完整代碼),你的大括號在語法上不是正確的。不知道你的全部源代碼,你可以嘗試這樣的:https://facebook.github.io/react/tips/if-else-in-JSX.html

render: function() { 
    var header; 

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

我s ee,謝謝! – 2015-02-06 01:12:34

+0

@NickBolsh,如果答案對你有用,你還應該點擊向上投票按鈕:-) – FakeRainBrigand 2015-02-06 02:39:51

+0

@FakeRainBrigand,你是對的!完成。 – 2015-02-06 03:01:20

0

做的if-else可以通過使用IIFE來完成的建議在這裏的另一種方式。

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

首先,您不能在一個語句中使用多個組件。 你必須這樣做:

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

好,爲大DOM,就像這樣:

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

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

BTW,我創建了一個小型圖書館做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 
) 
} 
...