在反应中,我试图为自定义 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 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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)