You need to enable JavaScript to run this app. React TypeScript 实现YouTube视频播放结束后启用继续按钮
优惠活动
大模型
产品
解决方案
定价
更多

React TypeScript 实现YouTube视频播放结束后启用继续按钮

实现方案

要实现视频播放完成才启用「继续」按钮的需求,核心是接入YouTube官方IFrame API监听播放结束事件,配合React状态控制按钮交互,同时解决TypeScript的类型兼容问题,具体调整方向:

  • 补充TypeScript对YouTube全局API的类型声明,避免编译报错
  • 新增isVideoEnded状态,初始值为false,作为按钮启用的判断依据
  • 在useEffect中加载YouTube官方SDK脚本,初始化播放器实例,绑定播放完成的事件回调
  • 给「继续」按钮添加禁用逻辑,同时拦截未完成播放时的路由跳转,避免违规触发链接跳转
  • 清理冗余的未使用代码(原代码中无实际调用的timeout函数)
完整可运行代码
import { Link } from "react-router-dom";
import Container from 'react-bootstrap/Container';
import { useEffect, useState } from "react";

// 补充YouTube API的TS类型声明,解决全局变量识别报错
declare global {
  interface Window {
    YT: any;
    onYouTubeIframeAPIReady: () => void;
  }
}

export function Video() {
  // 状态:标记视频是否播放完成
  const [isVideoEnded, setIsVideoEnded] = useState(false);

  useEffect(() => {
    // 避免重复加载SDK
    if (window.YT) return;

    // 加载YouTube IFrame SDK
    const tag = document.createElement('script');
    tag.src = "https://www.youtube.com/iframe_api";
    document.body.appendChild(tag);

    // SDK加载完成后的初始化逻辑
    window.onYouTubeIframeAPIReady = () => {
      new window.YT.Player('youtube-player', {
        videoId: 'iw5lP63fUxY',
        width: '560',
        height: '315',
        playerVars: {
          autoplay: 1,
          controls: 0,
          enablejsapi: 1, // 必须开启JS API才能监听播放事件
        },
        events: {
          // 监听播放结束事件
          onStateChange: (event: any) => {
            if (event.data === window.YT.PlayerState.ENDED) {
              setIsVideoEnded(true);
            }
          }
        }
      });
    };

    // 组件卸载时清理脚本引用,避免内存泄漏
    return () => {
      const existingScript = document.querySelector('script[src="https://www.youtube.com/iframe_api"]');
      if (existingScript) existingScript.remove();
    }
  }, []);

  return (
    <Container className="p-3">
      <div className="alert alert-info" role="alert">
        <h4 className="alert-heading"></h4>
        <p style={{ textAlign: "center" }}>
          <big> <b>  Please watch the video </b> </big>
          <br />
        </p>
        {/* 播放器容器,供API识别并渲染视频 */}
        <div 
          id="youtube-player"
          style={{
            marginLeft: "auto",
            marginRight: "auto",
            marginBottom: "40px",
            display: "block",
          }}
        />
        <p style={{ textAlign: "center" }}>
          <Link 
            to="/A"
            onClick={(e) => {
              // 视频未播放完成时拦截路由跳转
              if (!isVideoEnded) e.preventDefault();
            }}
          >
            <button 
              type="button" 
              className="btn btn-info"
              disabled={!isVideoEnded}
              style={{
                opacity: isVideoEnded ? 1 : 0.5,
                cursor: isVideoEnded ? 'pointer' : 'not-allowed'
              }}
            >
              Continue
            </button>
          </Link>
        </p>
      </div>
    </Container>
  );
}
核心注意事项
  • 必须在播放器参数中开启enablejsapi=1,否则SDK无法捕捉到播放状态变化
  • 包裹按钮的Link组件需要增加点击拦截逻辑,否则即使按钮处于禁用状态,外部链接仍会触发路由跳转
  • TypeScript环境下需要对window上挂载的YT全局变量做类型扩展,否则会出现“找不到YT对象”的编译错误
  • 组件卸载时需要清理动态加载的SDK脚本,避免内存泄漏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.28 01:06:01