Listview with alternating color in react native

后端 未结 4 813
一整个雨季
一整个雨季 2021-01-14 05:47

I have array of objects like the example below;

[{
        \"id\" : 13100,
        \"key\" : \"Emlak Vergisi\",
        \"y\" : 135638.98
    }, {
        \"         


        
相关标签:
4条回答
  • 2021-01-14 06:09

    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)

    0 讨论(0)
  • 2021-01-14 06:15
        (Provided Array).map((array, index) => {
            return (
                <View style={{ backgroundColor: (index % 2 == 0) ? '#ecf0f1' : '#fff' }}>
                    <Text>{array.key}</Text>
                </View>
            )
        })
    
    0 讨论(0)
  • 2021-01-14 06:16

    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>
          );
        }
      };
    
    0 讨论(0)
  • 2021-01-14 06:30

    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'}}/>);
    }
    
    0 讨论(0)
提交回复
热议问题