React Native02——FlatList

2019-12-17  本文已影响0人  LM林慕

FlatList

在RN0.43版本中引入了FlatList,SectionList与VirtualizedList,其中VirtualizedList是FlatList和SectionList的底层实现。

VirtualizedList

VirtualizedList是FlatList和SectionList的底层实现。VirtualizedList通过维护一个有限的渲染窗口(其中包含可见的元素),并将渲染窗口之外的元素全部用合适的定长空白空间代替的方式,极大的改善了内存使用,提高了大量数据情况下的渲染性能。这个渲染窗口能响应滚动行为,元素离可视区越远优先级越低,越近优先级越高,当用户滑动速度过快时,会出现短暂空白的情况。

[图片上传失败...(image-dba3f3-1576587151461)]

PureComponent

PureComponent是Component的一个优化组件,在React中的渲染性能有了大的提升,可以减少不必要的 render操作的次数,从而提高性能。PureComponent 与Component 的生命周期几乎完全相同,但 PureComponent 通过prop和state的浅对比可以有效的减少shouldComponentUpate()被调用的次数。

特性

完全跨平台。

支持水平布局模式。

行组件显示或隐藏时可配置回调事件。

支持单独的头部组件。

支持单独的尾部组件。

支持自定义行间分隔线。

支持下拉刷新。

支持上拉加载。

支持跳转到指定行(ScrollToIndex)。
如果需要分组/类/区(section),请使用SectionList(这个我们会在之后的文章中介绍)

方法

Demo

FlatList

import React, { Component } from "react";
import {
  FlatList,
  StyleSheet,
  Text,
  View,
  RefreshControl,
  ActivityIndicator
} from "react-native";

type Props = {};
const CITY_NAMES = [
  "北京",
  "上海",
  "广州",
  "深圳",
  "杭州",
  "苏州",
  "成都",
  "武汉",
  "郑州",
  "洛阳",
  "厦门",
  "青岛",
  "拉萨"
];
export default class FlatListDemo extends Component<Props> {
  constructor(props) {
    super(props);
    this.state = {
      dataArray: CITY_NAMES,
      isLoading: false
    };
  }

  _renderItem(data) {
    return (
      <View style={styles.item}>
        <Text style={styles.text}>{data.item}</Text>
      </View>
    );
  }

  loadData(refresh) {
    if (refresh) {
      this.setState({
        isLoading: true
      });
    }
    setTimeout(() => {
      let dataArray = [];
      if (refresh) {
        for (let i = this.state.dataArray.length - 1; i >= 0; i--) {
          dataArray.push(this.state.dataArray[i]);
        }
      } else {
        dataArray = this.state.dataArray.concat(CITY_NAMES);
      }
      this.setState({
        dataArray: dataArray,
        isLoading: false
      });
    }, 2000);
  }

  genIndicator() {
    return (
      <View style={styles.indicatorContainer}>
        <ActivityIndicator
          style={styles.indicator}
          size="large"
          animating={true}
        />
        <Text>正在加载更多</Text>
      </View>
    );
  }

  render() {
    return (
      <View style={styles.container}>
        <FlatList
          data={this.state.dataArray}
          renderItem={data => this._renderItem(data)}
          // refreshing={this.state.isLoading}
          // onRefresh={() => {
          //     this.loadData();
          // }}
          refreshControl={
            <RefreshControl
              title="Loading..."
              colors={["red"]}
              refreshing={this.state.isLoading}
              onRefresh={() => this.loadData(true)}
              tintColor={"orange"}
            />
          }
          ListFooterComponent={() => this.genIndicator()}
          onEndReached={() => {
            setTimeout(()=>{
              if(this.canLoadMore){
                    this.loadData();
                    this.canLoadMore = false
              }  
            },100)  
          }}
          onMomentumScrollBegin={()=>{
            this.canLoadMore = true;
          }}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  item: {
    height: 200,
    backgroundColor: "#169",
    marginLeft: 15,
    marginRight: 15,
    marginBottom: 15,
    alignItems: "center",
    justifyContent: "center"
  },
  text: {
    color: "white",
    fontSize: 20
  },
  indicatorContainer: {
    alignItems: "center"
  },
  indicator: {
    color: "red",
    margin: 10
  }
});

SwipeableFlatListDemo

import React, { Component } from "react";
import {
  ActivityIndicator,
  RefreshControl,
  StyleSheet,
  SwipeableFlatList,
  Text,
  TouchableHighlight,
  View
} from "react-native";

type Props = {};
const CITY_NAMES = [
  "北京",
  "上海",
  "广州",
  "深圳",
  "杭州",
  "苏州",
  "成都",
  "武汉",
  "郑州",
  "洛阳",
  "厦门",
  "青岛",
  "拉萨"
];
export default class SwipeableFlatListDemo extends Component<Props> {
  constructor(props) {
    super(props);
    this.state = {
      dataArray: CITY_NAMES,
      isLoading: false
    };
  }

  _renderItem(data) {
    return (
      <View style={styles.item}>
        <Text style={styles.text}>{data.item}</Text>
      </View>
    );
  }

  loadData(refresh) {
    if (refresh) {
      this.setState({
        isLoading: true
      });
    }
    setTimeout(() => {
      let dataArray = [];
      if (refresh) {
        for (let i = this.state.dataArray.length - 1; i >= 0; i--) {
          dataArray.push(this.state.dataArray[i]);
        }
      } else {
        dataArray = this.state.dataArray.concat(CITY_NAMES);
      }
      this.setState({
        dataArray: dataArray,
        isLoading: false
      });
    }, 2000);
  }

  genIndicator() {
    return (
      <View style={styles.indicatorContainer}>
        <ActivityIndicator
          style={styles.indicator}
          size="large"
          animating={true}
        />
        <Text>正在加载更多</Text>
      </View>
    );
  }

  genQuickActions(rowData, sectionID, rowID) {
    return (
      <View style={styles.quickContainer}>
        <TouchableHighlight
          onPress={() => {
            alert("确认删除");
          }}
        >
          <View style={styles.quick}>
            <Text style={styles.text}>删除</Text>
          </View>
        </TouchableHighlight>
      </View>
    );
  }

  render() {
    return (
      <View style={styles.container}>
        <SwipeableFlatList
          ref={swipe => (this.swipe = swipe)}
          data={this.state.dataArray}
          renderItem={data => this._renderItem(data)}
          refreshControl={
            <RefreshControl
              title="Loading..."
              colors={["red"]}
              refreshing={this.state.isLoading}
              onRefresh={() => this.loadData(true)}
              tintColor={"orange"}
            />
          }
          ListFooterComponent={() => this.genIndicator()}
          onEndReached={() => {
            this.loadData();
          }}
          //默认false,如果设置为true,会向用户展示滑动效果,提示用户可以滑动
          bounceFirstRowOnMount={false}
          //设置最大滑动距离
          maxSwipeDistance={60}
          //用于创建侧滑菜单
          renderQuickActions={() => this.genQuickActions()}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  item: {
    height: 100,
    backgroundColor: "#169",
    marginLeft: 15,
    marginRight: 15,
    marginBottom: 15,
    alignItems: "center",
    justifyContent: "center"
  },
  text: {
    color: "white",
    fontSize: 20
  },
  indicatorContainer: {
    alignItems: "center"
  },
  indicator: {
    color: "red",
    margin: 10
  },
  quickContainer: {
    flex: 1,
    flexDirection: "row",
    justifyContent: "flex-end",
    marginRight: 15,
    marginBottom: 15
  },
  quick: {
    backgroundColor: "red",
    flex: 1,
    alignItems: "flex-end",
    justifyContent: "center",
    padding: 10,
    paddingHorizontal: 10,
    width: 200
  }
});

SectionListDemo

import React, { Component } from "react";
import {
  SectionList,
  StyleSheet,
  Text,
  View,
  RefreshControl,
  ActivityIndicator
} from "react-native";

type Props = {};
const CITY_NAMES = [
  { data: ["北京", "上海", "广州", "深圳"], title: "一线" },
  {
    data: ["杭州", "苏州", "成都", "武汉"],
    title: "二三线1"
  },
  { data: ["郑州", "洛阳", "厦门", "青岛", "拉萨"], title: "二三线2" }
];
export default class SectionListDemo extends Component<Props> {
  constructor(props) {
    super(props);
    this.state = {
      dataArray: CITY_NAMES,
      isLoading: false
    };
  }

  _renderItem(data) {
    return (
      <View style={styles.item}>
        <Text style={styles.text}>{data.item}</Text>
      </View>
    );
  }

  _renderSectionHeader({ section }) {
    return (
      <View style={styles.sectionHeader}>
        <Text style={styles.text}>{section.title}</Text>
      </View>
    );
  }

  loadData(refresh) {
    if (refresh) {
      this.setState({
        isLoading: true
      });
    }
    setTimeout(() => {
      let dataArray = [];
      if (refresh) {
        for (let i = this.state.dataArray.length - 1; i >= 0; i--) {
          dataArray.push(this.state.dataArray[i]);
        }
      } else {
        dataArray = this.state.dataArray.concat(CITY_NAMES);
      }
      this.setState({
        dataArray: dataArray,
        isLoading: false
      });
    }, 2000);
  }

  genIndicator() {
    return (
      <View style={styles.indicatorContainer}>
        <ActivityIndicator
          style={styles.indicator}
          size="large"
          animating={true}
        />
        <Text>正在加载更多</Text>
      </View>
    );
  }

  render() {
    return (
      <View style={styles.container}>
        <SectionList
          //数据源
          sections={this.state.dataArray}
          renderItem={data => this._renderItem(data)}
          //分组标题组件
          renderSectionHeader={data => this._renderSectionHeader(data)}
          
          refreshControl={
            <RefreshControl
              title="Loading..."
              colors={["red"]}
              refreshing={this.state.isLoading}
              onRefresh={() => this.loadData(true)}
              tintColor={"orange"}
            />
          }
          ListFooterComponent={() => this.genIndicator()}
          onEndReached={() => {
            this.loadData();
          }}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fafafa"
  },
  item: {
    height: 80,
    marginBottom: 15,
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: "white"
  },
  sectionHeader: {
    height: 50,
    backgroundColor: "#93ebbe",
    alignItems: "center",
    justifyContent: "center"
  },
  text: {
    fontSize: 20
  },
  indicatorContainer: {
    alignItems: "center"
  },
  indicator: {
    color: "red",
    margin: 10
  }
});

上一篇下一篇

猜你喜欢

热点阅读