如何在reactjs解决方案中集成Youtube iframe api

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

在做出反应时,我正在尝试为自定义youtube播放器创建一个组件,以便我可以引入一个新的播放器控件栏。形成youtube iframe API,提到使用以下代码创建一个播放器实例,

var tag = document.createElement('script');

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

  // 3. This function creates an <iframe> (and YouTube player)
  //    after the API code downloads.
  var player;
  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
      height: '390',
      width: '640',
      videoId: 'M7lc1UVf-VE',
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
  }

但是,当我尝试在反应组件生命周期方法(如componentDidUpdate)上使用此代码时,根本找不到YT实例。

对此有何解决方案?

javascript reactjs youtube-iframe-api
1个回答
2
投票

这是我最近为项目编写的YouTubeVideo React组件。

当组件安装完毕后,它会检查是否已加载YouTube iFrame API。

  • 如果是,则调用API直接创建新的YouTube播放器对象。
  • 如果没有,它首先等待脚本异步加载然后加载视频。

import PropTypes from 'prop-types';
import React from 'react';

import classes from 'styles/YouTubeVideo.module.css';

class YouTubeVideo extends React.PureComponent {
  static propTypes = {
    id: PropTypes.string.isRequired,
  };

  componentDidMount = () => {
    // On mount, check to see if the API script is already loaded

    if (!window.YT) { // If not, load the script asynchronously
      const tag = document.createElement('script');
      tag.src = 'https://www.youtube.com/iframe_api';

      // onYouTubeIframeAPIReady will load the video after the script is loaded
      window.onYouTubeIframeAPIReady = this.loadVideo;

      const firstScriptTag = document.getElementsByTagName('script')[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    } else { // If script is already there, load the video directly
      this.loadVideo();
    }
  };

  loadVideo = () => {
    const { id } = this.props;

    // the Player object is created uniquely based on the id in props
    this.player = new window.YT.Player(`youtube-player-${id}`, {
      videoId: id,
      events: {
        onReady: this.onPlayerReady,
      },
    });
  };

  onPlayerReady = event => {
    event.target.playVideo();
  };

  render = () => {
    const { id } = this.props;
    return (
      <div className={classes.container}>
        <div id={`youtube-player-${id}`} className={classes.video} />
      </div>
    );
  };
}

export default YouTubeVideo;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
© www.soinside.com 2019 - 2024. All rights reserved.