react-native的FlatList组件如何实现上拉加载、下拉刷新!

18 阅读1分钟

react-native的FlatList组件如何实现上拉加载、下拉刷新!直接上代码

/* 文章列表 */
import { useState } from 'react'
import {
  FlatList,
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  RefreshControl,
  Alert
} from 'react-native'
import { useRouter } from 'expo-router'

interface CoursesProps {
  id: number
  title: string
}

const Courses = () => {
  const router = useRouter()
  const [refreshing, setRrefreshing] = useState<boolean>(false)
  const [list] = useState<CoursesProps[]>([
    { id: 1, title: '天地玄黄,宇宙洪荒。' },
    { id: 2, title: '日月盈昃,辰宿列张。' },
    { id: 3, title: '寒来暑往,秋收冬藏。' },
    { id: 4, title: '闰余成岁,律吕调阳。' },
    { id: 5, title: '云腾致雨,露结为霜。' },
    { id: 6, title: '金生丽水,玉出昆冈。' },
    { id: 7, title: '剑号巨阙,珠称夜光。' },
    { id: 8, title: '果珍李柰,菜重芥姜。' },
    { id: 9, title: '海咸河淡,鳞潜羽翔。' },
    { id: 10, title: '龙师火帝,鸟官人皇。' }
  ])

  // 下拉刷新
  const onRefresh = () => {
    setRrefreshing(true)
    const timer = setTimeout(() => {
      Alert.alert('刷新成功')
      setRrefreshing(false)
      clearTimeout(timer)
    }, 3000)
  }

  // 上拉加载更多
  const onEndReached = () => {
    Alert.alert('加载更多')
  }

  return (
    <FlatList<CoursesProps>
      refreshControl={
        <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
      }
      onEndReached={onEndReached}
      onEndReachedThreshold={0.1}
      data={list}
      renderItem={({ item }) => (
        <View>
          <Text>{item.title}</Text>
          <TouchableOpacity
            onPress={() => router.navigate(`/courses/${item.id}`)}
          >
            <Text style={styles.button}>查看详情</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={styles.button}
            onPress={() =>
              router.navigate({
                pathname: `/courses/[id]`,
                params: { id: item.id }
              })
            }
          >
            <Text style={styles.ButtonText}>查看详情(编程式跳转)</Text>
          </TouchableOpacity>
        </View>
      )}
      keyExtractor={(item) => item.id.toString()}
    />
  )
}

const styles = StyleSheet.create({
  button: {
    borderColor: 'pink',
    backgroundColor: 'yellow',
    width: 150
  },
  ButtonText: {
    textAlign: 'center',
    color: '#ff0083'
  }
})

export default Courses