React Typescript 重新渲染 Youtube 框架

问题描述 投票:0回答:1

我创建了一个 Youtube 播放器框架,并在我的 Player React.Component 中使用它。我第一次调用组件时,播放器加载正常,但如果我切换组件并第二次转到播放器组件,则 Youtube 播放器框架不会渲染...

 const PlayerFrame = ({ videoId }) => {
  useEffect(() => {
    const tag = document.createElement('script');
    tag.src = "https://www.youtube.com/iframe_api";
    const firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    let player;

    (window as any).onYouTubeIframeAPIReady = () => {
      player = new (window as any).YT.Player('player', {
        height: 1000,
        width: 1000,
        videoId: videoId,
      });
    };

    return () => {
      (window as any).onYouTubeIframeAPIReady = null;
    };
  }, [videoId]);

  return (
    <div>
      <div id="player"></div>
    </div>
  );
};

export default PlayerFrame;
reactjs typescript youtube-api
1个回答
0
投票

发生这种情况可能是因为 onYouTubeIframeAPIReady 函数设置为 null,但组件卸载时播放器实例未正确销毁。这里有一个建议:

const PlayerFrame = ({ videoId }) => {
  const playerRef = useRef(null);

  useEffect(() => {
    const tag = document.createElement('script');
    tag.src = "https://www.youtube.com/iframe_api";
    const firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    const onYouTubeIframeAPIReady = () => {
      playerRef.current = new (window as any).YT.Player('player', {
        height: '1000',
        width: '1000',
        videoId: videoId,
        events: {
          onReady: (event) => {
            // Optionally do something when player is ready
          },
          onStateChange: (event) => {
            // Handle state changes if necessary
          }
        }
      });
    };

    (window as any).onYouTubeIframeAPIReady = onYouTubeIframeAPIReady;

    return () => {
      if (playerRef.current) {
        playerRef.current.destroy();
      }
      (window as any).onYouTubeIframeAPIReady = null;
    };
  }, [videoId]);

  return (
    <div>
      <div id="player"></div>
    </div>
  );
};

export default PlayerFrame;

希望能帮到你。

© www.soinside.com 2019 - 2024. All rights reserved.