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

React项目集成JW Player报错:Uncaught TypeError: window.jwplayer is not a function

React集成JW Player常见问题排查与修复方案

我尝试在React项目中集成JW Player,但控制台报错,参考教程编写了如下代码:

VideoPlayer组件代码

import { useEffect, useRef } from "react";

const VideoPlayer = ({ video }) => {
  const playerRef = useRef(null);

  useEffect(() => {
    if (playerRef.current && typeof window !== "undefined") {
      window.jwplayer(playerRef.current).setup({
        file: video.sourceUrl,
        width: "100%",
        aspectratio: "16:9",
      });
    }
  }, [video]);

  return <div ref={playerRef}></div>;
};

export default VideoPlayer;

App组件代码

import VideoPlayer from './VideoPlayer';

const video = {
  sourceUrl: 'https://cdn.jwplayer.com/manifests/EXAMPLE.m3u8',
};

const App = () => {
  return <VideoPlayer video={video} />;
};

export default App;

常见报错原因及修复步骤

  • 缺失JW Player SDK引入:代码直接调用window.jwplayer但未加载SDK,需在项目入口HTML文件(如public/index.html)中添加脚本:
    <script src="https://cdn.jwplayer.com/libraries/你的许可证密钥.js"></script>
    
  • 未处理播放器实例清理:组件卸载时未销毁播放器会引发内存泄漏,修改useEffect添加清理逻辑:
    import { useEffect, useRef } from "react";
    
    const VideoPlayer = ({ video }) => {
      const playerRef = useRef(null);
      const playerInstance = useRef(null);
    
      useEffect(() => {
        if (!window.jwplayer || !playerRef.current) return;
    
        playerInstance.current = window.jwplayer(playerRef.current).setup({
          file: video.sourceUrl,
          width: "100%",
          aspectratio: "16:9",
        });
    
        return () => {
          playerInstance.current?.remove();
        };
      }, [video]);
    
      return <div ref={playerRef}></div>;
    };
    
    export default VideoPlayer;
    
  • 许可证密钥未配置:付费版JW Player必须指定密钥,可在setup中添加:
    window.jwplayer(playerRef.current).setup({
      // 其他配置
      key: "你的JW Player许可证密钥"
    });
    
  • 无效视频资源地址:示例中的EXAMPLE.m3u8是占位符,需替换为真实有效的、JW Player支持格式(HLS/MP4等)的视频地址。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 23:03:17