You need to enable JavaScript to run this app. 使用react-player时如何实现视频播放1分钟后自动显示按钮
优惠活动
大模型
产品
解决方案
定价
更多

使用react-player时如何实现视频播放1分钟后自动显示按钮

实现逻辑说明

react-player 的 onProgress 回调会返回携带播放进度信息的对象,其中playedSeconds字段代表当前已播放的秒数,你只需要基于该字段判断是否达到60秒(1分钟),再控制按钮显隐即可。

你原有代码的问题是:onProgress的参数写法错误,没有读取真实播放进度值,只要播放进度回调触发就会直接显示按钮,不符合需求。


修改后的完整代码

import { useState } from 'react'
import ReactPlayer from 'react-player'
import { StaticImage } from 'gatsby-plugin-image' // 若使用gatsby静态图片组件保留该引入即可

const Page = () => {
    const [play, setPlay] = useState(false)
    const [showButton, setShowButton] = useState(false)
    
    function playVideo() {
        setPlay(true);
    }

    // 处理播放进度更新
    const handleProgress = (progress) => {
        // progress对象包含played、playedSeconds、loaded、loadedSeconds四个属性
        const { playedSeconds } = progress
        // 播放时长达到60秒且按钮尚未显示时才更新状态,减少不必要的重渲染
        if (playedSeconds >= 60 && !showButton) {
            setShowButton(true)
        }
        // 如果需求是进度回退到1分钟以内要隐藏按钮,可补充以下逻辑
        // else if (playedSeconds < 60 && showButton) {
        //   setShowButton(false)
        // }
    }
    
    return(
    <div>
        <div className="relative">
             <div className="embed-responsive aspect-ratio-16/9">
                    <ReactPlayer 
                        className="embed-responsive-item"
                        url="https://vimeo.com/126060304"
                        width="100%"
                        height="100%"
                        onProgress={handleProgress}
                        controls={true}
                        playing={play}
                        ></ReactPlayer>
                        <div className={`cursor-pointer absolute inset-0 ${play === true ? 'hidden' : ''}`} onClick={playVideo} onKeyDown={playVideo} aria-hidden="true">
                             <StaticImage src="../../images/play-overlay.png" alt="overlay" />
                        </div>
                </div>
           </div>
           {showButton && (
              <button>next</button>
           )}
       </div>
    )
}

export default Page

补充说明

  • 该逻辑会覆盖用户拖动进度条直接跳到1分钟之后的场景,如果需要禁止用户快进触发按钮,可以额外添加真实播放时长的统计逻辑,只有实际播放累计达到60秒才展示按钮。
  • onProgress默认每250ms触发一次,触发频率可以通过progressInterval属性自定义调整,单位为毫秒。

内容的提问来源于stack exchange,提问作者fjie

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 00:06:07