gpt4 book ai didi

javascript - 如何在 reactjs 解决方案中集成 Youtube Iframe api

转载 作者:行者123 更新时间:2023-11-30 07:12:15 25 4
gpt4 key购买 nike

在 react 中,我正在尝试为自定义 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
}
});
}

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

有什么解决办法吗?

最佳答案

这是我最近为一个项目编写的 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>

关于javascript - 如何在 reactjs 解决方案中集成 Youtube Iframe api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54017100/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com