Listview with alternating color in react native

拜拜、爱过 提交于 2019-12-01 06:09:29

问题


I have array of objects like the example below;

[{
        "id" : 13100,
        "key" : "Emlak Vergisi",
        "y" : 135638.98
    }, {
        "id" : 13154,
        "key" : "Çevre Temizlik ",
        "y" : 956.17
    }, {
        "id" : 19998,
        "key" : "Genel Tahakkuk",
        "y" : 89030.62
    }, {
        "id" : 24998,
        "key" : "Gecekondu ve So",
        "y" : 42721.07
    }, {
        "id" : 60000,
        "key" : "Ortak Gelirler",
        "y" : 827.42
    }
]

Is it possible to have a listview with alternating color for each item?


回答1:


I would say this approach is cleaner:

 renderRow(rowData, sectionID, rowID) {

   let style = [
         styles.row, 
         {'backgroundColor': colors[rowID % colors.length]}
       ];

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

 let colors = ['#123456', '#654321', '#fdecba', '#abcdef'];

 let styles = StyleSheet.create({
       row: {
            // .. rows style
       }
 });

This way you can easily add a specail color to each row in the list (not only by even/odd type)




回答2:


Yes in renderRow, apply a different style based on rowID or rowData etc

Ex:

renderRow(rowData, sectionID, rowID, highlightRow) {
    if(rowID%2 === 0) {
        return (<View style={{backgroundColor: 'blue'}}/>);
    }
    return (<View style={{backgroundColor: 'red'}}/>);
}



回答3:


You can use the rowId provided in the renderRow function. I've set up a working example here

Render row method :

  renderRow = (rowData, sectionId, rowId) => {
    if (rowId % 2) {
      return (
        <View style={{backgroundColor: 'red'}}>
          <Text>{rowData.id}</Text>
        </View>
      );
    } else {
      return (
        <View style={{backgroundColor: 'blue'}}>
          <Text>{rowData.id}</Text>
        </View>
      );
    }
  };



回答4:


    (Provided Array).map((array, index) => {
        return (
            <View style={{ backgroundColor: (index % 2 == 0) ? '#ecf0f1' : '#fff' }}>
                <Text>{array.key}</Text>
            </View>
        )
    })


来源:https://stackoverflow.com/questions/36127222/listview-with-alternating-color-in-react-native

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!