如何在React.js解决方案中集成Youtube Iframe API [英] How to integrate Youtube Iframe api in reactjs solution

查看:84
本文介绍了如何在React.js解决方案中集成Youtube Iframe API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为回应,我试图为自定义youtube播放器创建一个组件,以便引入一个新的播放器控件栏.形式为youtube iframe API,有人提到使用以下代码创建播放器实例

In react, I am trying to create a component for custom youtube player, so that I can introduce a new player controls bar. Form youtube iframe API, it was mentioned to use following code to create a player instance,

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
      }
    });
  }

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

But when I am trying to use this code on react component life-cycle methods (like componentDidUpdate) YT instance isn't found at all.

有什么解决办法吗?

推荐答案

这是我最近为一个项目编写的YouTubeVideo React组件.

Here is a YouTubeVideo React component I wrote for a project recently.

在安装组件时,它会检查YouTube iFrame API是否已经加载.

When the component mounts, it checks to see if the YouTube iFrame API has already been loaded.

  • 如果是,则它会调用API直接创建新的YouTube Player对象.
  • 如果没有,它将首先等待脚本异步加载,然后再加载视频.

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>

这篇关于如何在React.js解决方案中集成Youtube Iframe API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆