React自定义视频播放器章节功能异常:点击章节自动播放
React自定义视频播放器章节跳转逻辑修复
问题说明
开发带章节功能的自定义视频播放器时,点击章节按钮会出现以下问题:无论视频此前是否处于暂停状态,跳转至对应章节时间后都会自动开始播放,不符合预期需求。
预期目标
- 点击章节按钮,视频跳转至指定时间后保持暂停状态
- 仅当视频跳转前处于播放状态时,跳转完成后才继续播放
当前代码
import React, { useState, useRef } from 'react'; import './style.css'; const VideoPlayer = ({ src, chapters }) => { const videoRef = useRef(null); const [currentChapter, setCurrentChapter] = useState(null); const handleChapterClick = (chapter) => { if (videoRef.current) { videoRef.current.currentTime = chapter.time; console.log(videoRef.current.currentTime); videoRef.current.play(); } setCurrentChapter(chapter); }; return ( <div className="video-container"> <video ref={videoRef} controls className="video-player"> <source src={src} type="video/mp4" /> </video> <div className="chapters"> {chapters.map((chapter, index) => ( <button key={index} onClick={() => handleChapterClick(chapter)}> {chapter.title} </button> ))} </div> </div> ); }; export default VideoPlayer;
解决方案
核心思路是记录跳转前的视频播放状态,再根据状态决定是否继续播放:
- 在点击章节时,先通过
videoRef.current.paused获取当前视频是否处于暂停状态 - 跳转至目标时间后,仅当跳转前视频处于播放状态(即
paused为false)时,才调用play()方法 - 移除原代码中固定调用的
videoRef.current.play(),替换为条件判断逻辑
修改后的完整代码
import React, { useState, useRef } from 'react'; import './style.css'; const VideoPlayer = ({ src, chapters }) => { const videoRef = useRef(null); const [currentChapter, setCurrentChapter] = useState(null); const handleChapterClick = (chapter) => { if (videoRef.current) { // 记录跳转前的播放状态 const wasPlaying = !videoRef.current.paused; // 跳转至章节时间 videoRef.current.currentTime = chapter.time; console.log(videoRef.current.currentTime); // 仅当之前处于播放状态时,才继续播放 if (wasPlaying) { videoRef.current.play(); } } setCurrentChapter(chapter); }; return ( <div className="video-container"> <video ref={videoRef} controls className="video-player"> <source src={src} type="video/mp4" /> </video> <div className="chapters"> {chapters.map((chapter, index) => ( <button key={index} onClick={() => handleChapterClick(chapter)}> {chapter.title} </button> ))} </div> </div> ); }; export default VideoPlayer;
内容的提问来源于stack exchange,提问作者Tuvshu247
相关产品推荐
相关产品推荐

