【问题标题】:Listview with alternating color in react native在本机反应中具有交替颜色的列表视图
【发布时间】:2016-03-21 09:29:14
【问题描述】:

我有一个对象数组,如下例所示;

[{
        "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
    }
]

是否可以为每个项目创建一个具有交替颜色的列表视图?

【问题讨论】:

    标签: react-native react-native-listview


    【解决方案1】:

    我会说这种方法更干净:

     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
           }
     });
    

    通过这种方式,您可以轻松地为列表中的每一行添加特殊颜色(不仅是偶数/奇数类型)

    【讨论】:

      【解决方案2】:

      在 renderRow 中是,根据 rowID 或 rowData 等应用不同的样式

      例如:

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

      【讨论】:

      • 非常感谢。 RowId 正是我所需要的。
      【解决方案3】:

      您可以使用 renderRow 函数中提供的 rowId。我已经建立了一个工作示例here

      渲染行方法:

        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>
                )
            })
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-11-03
          • 2017-08-18
          • 2021-09-28
          • 1970-01-01
          • 1970-01-01
          • 2022-06-30
          相关资源
          最近更新 更多