作为回应,我试图为自定义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实例。
有什么解决办法吗?
答案 0 :(得分:1)
这是我最近为一个项目编写的YouTubeVideo React组件。
在安装组件时,它会检查YouTube iFrame API是否已经加载。
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>