2017-02-28 59 views
12

是否有可能在渲染函數中循環相同的組件?如何在React-native中循環和渲染元素?

事情是這樣的:

... 

onPress =() => { 
... 
}; 

initialArr = [["blue","text1"],["red","text2"]]; 
buttonsListArr = []; 

for (let i = 0; i < initialArr.length; i++) 
{ 
buttonsListArr.push(
    <Button style={{borderColor:{initialArr[i][0]}}} onPress={this.onPress.bind(this)}>{initialArr[i][1]}</Button> 
); 
} 

... 

render() { 
    return (
    <View style={...}> 
    {buttonsListArr} 
    </View> 
)}; 

我的意思是,這是組件的只是有限的名單,所以喜歡的ListView /滾動型等任何組件並不適用於這種特殊情況下。這只是語法問題。

+0

爲什麼不用地圖代替?'''const button = buttonsListArr.map(item =>

回答

13

你通常會使用地圖的那種事情。

buttonsListArr = initialArr.map(buttonInfo => (
    <Button ... key={buttonInfo[0]}>{buttonInfo[1]}</Button> 
); 

(鍵是一個必要的道具每當你在陣營,關鍵需要是對所產生的組件的唯一標識符做映射)

作爲一個方面,我會用一個對象,而不是數組。我覺得它看起來更好:

initialArr = [ 
    { 
    id: 1, 
    color: "blue", 
    text: "text1" 
    }, 
    { 
    id: 2, 
    color: "red", 
    text: "text2" 
    }, 
]; 

buttonsListArr = initialArr.map(buttonInfo => (
    <Button ... key={buttonInfo.id}>{buttonInfo.text}</Button> 
); 
6
render() { 
    return (
    <View style={...}> 
     {initialArr.map((prop, key) => { 
     return (
      <Button style={{borderColor: prop[0]}} key={key}>{prop[1]}</Button> 
     ); 
     })} 
    </View> 
) 
} 

應該做的伎倆

+1

看起來不錯,但我會在返回之前的映射移到語句使事情看起來更好,只需在View中使用映射的數組變量名即可,作爲說明,映射函數的第二個參數是數組中元素的索引,儘管它們可能是一個不同的整數每次他們可能不一定是關鍵屬性的好候選者將會改變,因此密鑰也必須改變(如果您使用了唯一的標識符,則即使索引已更改,密鑰也會保持不變)。 – nbkhope

+2

根據React文檔,「如果項目可以重新排序,我們不推薦使用索引,因爲這樣會很慢。」 - https://facebook.github.io/react/docs/lists-and- keys.html(Keys部分,底部) – nbkhope

+0

@nbkhope這是關於密鑰的新信息。謝謝! – Damathryx

1

對於初始陣列,更好的使用對象,而不是數組,那麼你就不會擔心指標,這將是更清楚什麼是什麼:

const initialArr = [{ 
    color: "blue", 
    text: "text1" 
}, { 
    color: "red", 
    text: "text2" 
}]; 

對於實際映射,使用JS陣圖,而不是爲循環 - for循環應的情況下使用時,有沒有實際的數組定義,如顯示的東西一定NUM時間:

onPress =() => { 
    ... 
}; 

renderButtons() { 
    return initialArr.map((item) => { 
     return (
      <Button 
       style={{ borderColor: item.color }} 
       onPress={this.onPress} 
      > 
       {item.text} 
      </Button> 
     ); 
    }); 
} 

... 

render() { 
    return (
     <View style={...}> 
      { 
       this.renderButtons() 
      } 
     </View> 
    ) 
} 

我將映射移動到render方法之外的單獨函數以獲得更多可讀代碼。 還有很多其他的方式可以循環使用native native中的元素列表,您將使用哪種方式取決於您需要做什麼。大多數這些方法在this article about React JSX loops中都有介紹,雖然它使用的是React示例,但它的所有內容都可以在React Native中使用。如果你對這個主題感興趣,請查看它!

另外,不是關於循環的主題,但是因爲您已經使用數組語法來定義onPress函數,所以不需要再次綁定它。這也適用於只有在組件內使用此語法定義函數的情況,因爲箭頭語法會自動綁定該函數。