React Native填坑之旅--ListView的Section Header

本文介绍了在React Native中利用ListView的Section功能为数据分组,并创建Section Header。当添加Section和Header后,iOS平台上的行为将与iOS的TableView保持一致。在数据源、绘制和整体拼接方面进行了详细阐述,包括如何处理数据源变化、实现Section Header的绘制,并提供了部分关键代码示例。

React Native自己实现的ListView还有一个隐藏功能那就是Section。Section在文档里连一句话都没有给足,但确确实实的是内置的。使用Section可以给数据分组,并且每一个Section都有一个Header。Section Header可以像iOS的TableView的Section Header一样在滑动的时候保持当前的Section Header浮动在Table View的最上部。

在iOS上,只要添加了Section和Section Header以后,Section Header的行为就一定是和iOS的TableView的Section Header 一致的。这个在Android上还没有测试。

数据源的变化

要使用Section,那么首先一开始就需要告诉数据源不仅要考虑行的变化还要考虑Section Header的变化:

    const ds = new ListView.DataSource({
      rowHasChanged: (r1, r2) => r1 !== r2,
      sectionHeaderHasChanged: (s1, s2) => s1 !== s2
    });

然后就要考虑数据的变化了。之前只需要一个数组就可以完成的,现在需要数据可以明确的区分出Section。最简单的一个数据源应该是这样的:

    this.state = {
      dataSource: ds.cloneWithRowsAndSections({
        'section1': ['1'],
        'section2': ['row 1', 'row 2', 'row 1', 'row 2', 'row 1', 'row 2', 'row 1', 'row 2', 'row 1', 'row 2', 'row 1', 'row 2']
      })
    };

单独的看数据是这样的一个形式:

    {
        'section1': ['1'],
        'section2': ['row 1', 'row 2', 'row 1', 'row 2', 'row 1', 'row 2', 'row 1', 'row 2', 'row 1', 'row 2', 'row 1', 'row 2']
    }

绘制的变化

在没有Section的时候,绘制很简单。只需要实现一个renderRow的方法。现在就需要考虑绘制Section Header了,方法就是renderSectionHeader。和renderRow方法一样,两个方法都是返回一个视图组件。比如:

  _renderSectionHeader(data, sectionID) {
    if (sectionID === 'section1') {
      return null
    }
    return (
      <View style={styles.section}>
        <View style={{flex: 1}}><Text>category 1</Text></View>
        <View style={{flex: 1}}><Text>category 2</Text></View>
        <View style={{flex: 1}}><Text>category 3</Text></View>
      </View>
    );
  }

拼接起来

以上的内容就是使用一个Section方法都需要的只是了。非常简单,但是官网居然不把这些内容放出来。

下面贴出了ListView 部分的代码,完整代码可以移步这里

/*
 * Copy Right 2016 Uncle Charlie
 *
 * @flow
*/

import React, { Component } from 'react';
import {
  View,
  Text,
  ListView,
  StyleSheet
} from 'react-native';

export default class SectionListView extends Component {
  state: {dataSource: any};

  constructor(props: any) {
    super(props);

    const ds = new ListView.DataSource({
      rowHasChanged: (r1, r2) => r1 !== r2,
      sectionHeaderHasChanged: (s1, s2) => s1 !== s2
    });

    this.state = {
      dataSource: ds.cloneWithRowsAndSections({
        'section1': ['1'],
        'section2': ['row 1', 'row 2', 'row 1', 'row 2', 'row 1', 'row 2', 'row 1', 'row 2', 'row 1', 'row 2', 'row 1', 'row 2']
      })
    };

    this._renderRow = this._renderRow.bind(this);
    this._renderSectionHeader = this._renderSectionHeader.bind(this);
  }

  _renderRow(data, sectionID, rowID) {
    let heightStyle = (sectionID === 'section1' && rowID === '0') ?
      {height: 100, backgroundColor: 'white'} :
      {}

    return (
      <View style={[styles.row, heightStyle]}>
        <Text>{data}</Text>
      </View>
    );
  }

  _renderSectionHeader(data, sectionID) {
    if (sectionID === 'section1') {
      return null
    }
    return (
      <View style={styles.section}>
        <View style={{flex: 1}}><Text>category 1</Text></View>
        <View style={{flex: 1}}><Text>category 2</Text></View>
        <View style={{flex: 1}}><Text>category 3</Text></View>
      </View>
    );
  }

  render() {
    return (
      <ListView style={styles.list}
        dataSource={this.state.dataSource}
        renderRow={this._renderRow}
        renderSectionHeader={this._renderSectionHeader}
        />
    );
  }
}

var styles = StyleSheet.create({
  list: {
    marginTop: 64,
  },
  row: {
    height: 50,
    backgroundColor: 'white'
  },
  section: {
    height: 30,
    backgroundColor: 'green',
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center'
  }
});
我使用https://github.com/gaokaikai/react-native-smart-refresh.git该仓库,想用RefreshAnimateHeader 来实现下拉刷新动画 但是没有任何效果。这是我的代码import React, { useState } from 'react'; import { SafeAreaView, StyleSheet, ScrollView, View, Text, StatusBar, Dimensions } from 'react-native'; import { Header, LearnMoreLinks, Colors, DebugInstructions, ReloadInstructions } from 'react-native/Libraries/NewAppScreen'; import { RefreshAnimateHeader, RefreshNormalHeader } from 'react-native-smart-refresh'; // 获取屏幕尺寸 const { width, height } = Dimensions.get('window'); const SunColor = '#FFD700'; const App = () => { const [refreshing, setRefreshing] = useState(false); const [isRefreshing, setIsRefreshing] = useState(false); const onRefresh = () => { // 模拟刷新逻辑 setRefreshing(true); setIsRefreshing(true); setTimeout(() => { setRefreshing(false); setIsRefreshing(false); }, 2000); }; return ( <> <ScrollView contentContainerStyle={styles.scrollViewContent} refreshControl={ <RefreshAnimateHeader refreshing={isRefreshing} onRefresh={onRefresh} containerStyle={{ marginBottom: 0, alignItems: 'flex-end' }} /> } > </ScrollView> </> ); }; const styles = StyleSheet.create({ safeArea: { flex: 1, paddingTop: StatusBar.currentHeight // 避免内容被刘海遮挡 }, scrollViewContent: { padding: 16, minHeight: height // 确保 ScrollView 有足够的高度可滑动 }, text: { fontSize: width * 0.05, marginVertical: 8 }, scrollView: { backgroundColor: Colors.lighter, }, engine: { position: 'absolute', right: 0, }, body: { backgroundColor: Colors.white, }, sectionContainer: { marginTop: 32, paddingHorizontal: 24, }, sectionTitle: { fontSize: 24, fontWeight: '600', color: Colors.black, }, sectionDescription: { marginTop: 8, fontSize: 18, fontWeight: '400', color: Colors.dark, }, highlight: { fontWeight: '700', }, footer: { color: Colors.dark, fontSize: 12, fontWeight: '600', padding: 4, paddingRight: 12, textAlign: 'right', }, container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, lottie: { width: 300, height: 300, }, }); export default App; 请帮我修改错误,并且给出正确的代码
最新发布
10-12
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值