2017-07-26 215 views
0
<div className="feedback"> 
    {(this.state.finished) ? questions.map(function(x, index) { return 
    <div> 
    </div> 
    }) : null} 
</div>  

所以我現在有上面的代碼。我想在另一塊的js代碼this.state.score而不是內部的地圖功能添加這樣的,因爲我只希望它渲染一次(目前它呈現每次映射陣列上的時間)如何正確渲染jsx

<div className="feedback"> 
    {(this.state.finished) ? {this.state.score} //WANT TO ADD IT HERE questions.map(function(x, index) { return 
    <div> 
    </div> 
    }) : null} 
</div> 

,但是這並未」工作。所以我怎麼在這裏添加我的代碼?我也需要它在三元內

回答

2

JSX中的三元表達式必須返回一個數組或單個節點,類似於React的render方法必須只返回單個節點。

<div className="feedback"> 
    { (this.state.finished) ? 
     <div> 
     {this.state.score} 
     {questions.map(function(x, index) { 
      return <div></div> 
     })} 
     </div> 
     : 
     null 
    } 
</div> 

現在,在單個節點三元結果(一<div>),基本上「包裝」要有條件地渲染所有的東西。另外請注意,questions.map包裝在花括號{}中,因爲您在內嵌更多內聯JavaScript的JSX內嵌入了內聯JavaScript。