You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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;

解决方案

核心思路是记录跳转前的视频播放状态,再根据状态决定是否继续播放:

  1. 在点击章节时,先通过videoRef.current.paused获取当前视频是否处于暂停状态
  2. 跳转至目标时间后,仅当跳转前视频处于播放状态(即paused为false)时,才调用play()方法
  3. 移除原代码中固定调用的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 11:42:45