2017-09-08 55 views
2

地圖函數內部陣列我有一個函數:遍歷在反應天然

renderConversations(){ 
    let conversationContent = this.state.conversationArray.map((convObj, i) => { 
     return <View key={i} style={[globalStyle.conversationContainer,globalStyle.shadow]}> 
     <Text style= {globalStyle.conversationText}>{ convObj.text }</Text> 
     <Text style= {globalStyle.conversationText}>{ convObj.actionButtons }</Text> 
     </View>        
    }) 
    return conversationContent 
    } 

我渲染使用根據狀態變量此功能的組件。我面臨的挑戰是convObj.actionButtons這裏是一個數組。我想在map函數內部迭代構建組件。有沒有辦法在map函數中執行此操作,還是需要使用good for for循環?

+1

是的,這將是正確的方法,使用另一種映射,並創建UI元素:) –

回答

2

有沒有辦法到內做到這一點地圖功能?

是的,這將是動態創建UI元素的正確方法。再次使用地圖並創建元素。

檢查這個例子:

renderConversations(){ 
    let conversationContent = this.state.conversationArray.map((convObj, i) => { 
     return <View key={i} style={[globalStyle.conversationContainer,globalStyle.shadow]}> 
      <Text style= {globalStyle.conversationText}>{ convObj.text }</Text> 
      <Text style= {globalStyle.conversationText}> 
       { 
        convObj.actionButtons.map((el, j) => { 

         return /*Code*/ 

        }) 
       } 
      </Text> 
     </View>        
    }) 
    return conversationContent 
} 

我需要用好老for循環?

您可以使用,但也使用地圖會很容易,因爲我們直接不能爲內部循環JSX用,所以你需要創建另一個函數,並把所有的for循環邏輯裏面那個和調用該函數從地圖。

像這樣:

renderConversations(){ 
    let conversationContent = this.state.conversationArray.map((convObj, i) => { 
     return <View key={i} style={[globalStyle.conversationContainer,globalStyle.shadow]}> 
      <Text style= {globalStyle.conversationText}>{ convObj.text }</Text> 
      <Text style= {globalStyle.conversationText}> 
       { 
        this._fun(convObj.actionButtons) 
       } 
      </Text> 
     </View>        
    }) 
    return conversationContent 
} 


_fun(item){ 
    //for loop here and return the elements 
} 
4

你可以使用第二個地圖但這會導致混亂。

如何使用一個單獨的函數返回第二映射數組:

renderActionButtons(actionButtons) { 
    return actionButtons.map(button => { 
    // Return code here 
    } 
} 

...然後這樣使用:

renderConversations() { 
    let conversationContent = this.state.conversationArray.map((convObj, i) => { 
    return <View key={i} style={[globalStyle.conversationContainer,globalStyle.shadow]}> 
     <Text style= {globalStyle.conversationText}>{ convObj.text }</Text> 
     <Text style= {globalStyle.conversationText}>{ this.renderActionButtons(convObj.actionButtons) }</Text> 
    </View>        
    }) 
    return conversationContent 
}