探索React Native Video Demo:构建跨平台视频应用的新里程
import React, { useRef, useEffect, useState } from 'react';
import { StyleSheet, View, Text, Button, Alert } from 'react-native';
import Video from 'react-native-video';
export default function VideoPlayer({ navigation }) {
const videoRef = useRef(null);
const [isPlaying, setIsPlaying] = useState(false);
useEffect(() => {
if (isPlaying) {
videoRef.current.playAsync();
} else {
videoRef.current.pauseAsync();
}
}, [isPlaying]);
const playPauseVideo = async () => {
try {
if (isPlaying) {
await videoRef.current.pauseAsync();
} else {
await videoRef.current.playAsync();
}
setIsPlaying(!isPlaying);
} catch (error) {
Alert.alert('Error', error.message);
}
};
return (
<View style={styles.container}>
<Video
ref={videoRef}
style={styles.video}
source={{ uri: 'http://d23dyxeqlo5psv.cloudfront.net/big_buck_bunny.mp4' }}
resizeMode="cover"
shouldPlay={isPlaying}
useNativeControls
/>
<Button title={isPlaying ? 'Pause' : 'Play'} onPress={playPauseVideo} />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#000',
},
video: {
width: '100%',
height: 300,
},
});
这段代码使用React Native Video组件构建了一个简单的视频播放器,并展示了如何使用useRef和useEffect来处理播放和暂停逻辑,以及如何使用useState管理播放状态。同时,代码中的try-catch块用于处理异步操作中可能出现的错误,并通过Alert组件显示错误信息。
评论已关闭