如何在跳转至其他页面时停止react-native-video的播放?
解决React Native欢迎页背景视频跳转页面时停止播放的问题
嘿,这个场景我太熟悉了!用react-native-video做背景视频时,跳转页面后视频还在后台播放确实很头疼,下面给你几个靠谱的解决思路,都是我实际项目里用过的:
方案1:利用组件生命周期(类组件)
如果你的欢迎页是类组件,可以在组件卸载的时候触发视频停止。首先需要给Video组件添加一个ref,然后在componentWillUnmount生命周期里调用视频的暂停/停止方法:
import React, { Component } from 'react'; import Video from 'react-native-video'; class WelcomeScreen extends Component { videoRef = null; componentWillUnmount() { // 组件卸载时停止视频播放 if (this.videoRef) { this.videoRef.pause(); // 或者用stop(),根据你的需求选择 // this.videoRef.stop(); } } render() { return ( <Video ref={ref => this.videoRef = ref} source={require('./background-video.mp4')} style={{ position: 'absolute', top: 0, left: 0, right: 0, bottom: 0 }} loop muted resizeMode="cover" /> ); } } export default WelcomeScreen;
方案2:函数组件用useEffect清理函数
如果是函数组件,就用useRef获取视频实例,然后在useEffect的清理回调里执行停止操作——这个清理函数会在组件卸载或者依赖项变化时触发:
import React, { useRef, useEffect } from 'react'; import Video from 'react-native-video'; const WelcomeScreen = ({ navigation }) => { const videoRef = useRef(null); useEffect(() => { // 组件卸载时执行的清理函数 return () => { if (videoRef.current) { videoRef.current.pause(); } }; }, []); return ( <Video ref={videoRef} source={require('./background-video.mp4')} style={{ position: 'absolute', top: 0, left: 0, right: 0, bottom: 0 }} loop muted resizeMode="cover" /> ); }; export default WelcomeScreen;
方案3:监听路由导航事件(更灵活)
如果你用的是React Navigation,还可以监听页面的失焦事件,这样不管是跳转到其他页面还是切换tab,只要当前页面不在前台,就停止视频播放。这种方式比仅依赖组件卸载更灵活,比如页面被切换但没卸载的场景也能处理:
import React, { useRef, useEffect } from 'react'; import Video from 'react-native-video'; import { useNavigation } from '@react-navigation/native'; const WelcomeScreen = () => { const videoRef = useRef(null); const navigation = useNavigation(); useEffect(() => { // 监听页面失焦事件 const unsubscribe = navigation.addListener('blur', () => { if (videoRef.current) { videoRef.current.pause(); } }); // 监听页面聚焦事件,需要的话可以恢复播放 const focusUnsubscribe = navigation.addListener('focus', () => { if (videoRef.current) { videoRef.current.play(); } }); // 清理监听事件 return () => { unsubscribe(); focusUnsubscribe(); }; }, [navigation]); return ( <Video ref={videoRef} source={require('./background-video.mp4')} style={{ position: 'absolute', top: 0, left: 0, right: 0, bottom: 0 }} loop muted resizeMode="cover" /> ); }; export default WelcomeScreen;
小提示
- 优先用
pause()而不是stop(),因为stop()会把视频进度重置到开头,下次播放需要重新加载;而pause()会保留当前进度,返回页面时可以继续播放。 - 确保
ref正确绑定到Video组件,不然调用方法会报错哦!
内容的提问来源于stack exchange,提问作者Anamul Haque
相关产品推荐
相关产品推荐

