在上一节中,我们完成了发现模块的数据请求逻辑。在本节中,我们将实现数据的展示功能。
一、创建发现页面组件
-
创建
Found文件夹和组件在
pages文件夹下创建Found文件夹,并将Found.ts文件移动到该文件夹中,重命名为index.ts。 -
使用
connect函数封装组件import React from 'react'; import { FlatList } from 'react-native'; import { connect, ConnectedProps } from 'react-redux'; import FoundItem from './FoundItem'; import { IFound } from '@/models/found'; interface IProps extends ConnectedProps<typeof connector> {} class Found extends React.PureComponent<IProps> { state = { list: [] as IFound[], }; componentDidMount() { const { dispatch } = this.props; dispatch({ type: 'found/fetchList', callback: (data: IFound[]) => { this.setState({ list: data, }); }, }); } renderItem = ({ item }: ListRenderItemInfo<IFound>) => { return <FoundItem item={item} />; }; render() { const { list } = this.state; return ( <FlatList data={list} renderItem={this.renderItem} keyExtractor={(item) => item.id} /> ); } } const connector = connect(); export default connector(Found);
二、创建列表项组件
-
创建
FoundItem组件在
Found文件夹中创建FoundItem.tsx文件:import React from 'react'; import { View, Text, StyleSheet } from 'react-native'; import { IFound } from '@/models/found'; interface IProps { item: IFound; } class FoundItem extends React.PureComponent<IProps> { render() { const { item } = this.props; return ( <View style={styles.item}> <Text style={styles.title}>{item.title}</Text> </View> ); } } const styles = StyleSheet.create({ item: { marginBottom: 10, }, title: { margin: 5, }, }); export default FoundItem;
三、安装视频播放依赖
-
安装
react-native-videoyarn add react-native-video -
安装类型定义文件
yarn add -D @types/react-native-video -
重新安装应用
yarn android cd ios && pod install cd ..
四、实现视频播放功能
-
安装视频控制组件
yarn add react-native-video-custom-controls -
更新
FoundItem组件import React from 'react'; import { View, StyleSheet } from 'react-native'; import VideoPlayer from 'react-native-video-custom-controls/dist/VideoPlayer'; import { IFound } from '@/models/found'; interface IProps { item: IFound; paused: boolean; } class FoundItem extends React.PureComponent<IProps> { render() { const { item, paused } = this.props; return ( <View style={styles.item}> <VideoPlayer paused={paused} source={{ uri: item.videoUrl }} style={styles.video} /> </View> ); } } const styles = StyleSheet.create({ item: { marginBottom: 10, }, video: { height: 220, }, }); export default FoundItem;
五、总结
在本节中,我们完成了发现模块的列表展示功能。通过使用 FlatList 和 react-native-video-custom-controls,我们实现了视频列表的展示和播放功能。下一节,我们将继续完善发现模块的功能。