import { FlatList, FlatListProps, Text, StyleSheet, View, ActivityIndicator, ViewStyle, } from 'react-native' import React, { ReactElement } from 'react' import variables from '../../common/styles/variables' const styles = StyleSheet.create({ loadingIndicator: { padding: 10, } }) export interface LonglistProps extends FlatListProps { data: Array total?: number onEndReached?: any onRefresh?: any renderFooter?: any initialNumToRender?: number } export class Longlist extends React.Component { flatList = null // 通过 flatList 对象,调用 FlatList 组件相关方法 static defaultProps = { total: 0, data: [], initialNumToRender: 5 } constructor(props) { super(props) this.state = { refreshing: false, loading: false, } } handleEndReached = () => { const { data, total, onEndReached } = this.props if (!onEndReached) { return } if (data && data.length && data.length >= total) { return } if (this.state.loading) { return } this.setState({ loading: true, }, () => { onEndReached().then(() => { this.setState({ loading: false }) }).catch((e) => { this.setState({ loading: false }) }) }) } handleRefresh = () => { if (this.state.refreshing) { return } this.setState({ refreshing: true }, () => { this.props.onRefresh().then(() => { this.setState({ refreshing: false, }) }).catch(() => { this.setState({ refreshing: false, }) }) }) } renderFooter() { const { data, total, renderFooter } = this.props const { loading } = this.state let footer = null if (renderFooter) { footer = renderFooter(loading, data, total) } if (React.isValidElement(footer)) { return footer } if (loading) { return ( ) } if (data && !data.length && total === 0) { return 无数据 } if (data && data.length && data.length >= total) { return 无更多数据 } return null } render() { const { refreshing } = this.state const { onRefresh } = this.props const retProps = { ...this.props, } as any if (!onRefresh) { delete retProps.refreshing delete retProps.onRefresh } else { retProps.refreshing = refreshing retProps.onRefresh = this.handleRefresh } return ( { this.flatList = c }} keyExtractor={(item, index) => { return index.toString() }} initialNumToRender={this.props.initialNumToRender} onEndReached={this.handleEndReached} onEndReachedThreshold={0.1} ListFooterComponent={() => { return this.renderFooter() }} /> ) } }