使用YouTubes JS API和Reactjs渲染iFrame视频
Render iFrame video using YouTubes JS API with Reactjs
我试着寻找周围的例子,但我所有的是youtube-react
npm
包,我不想,因为我想这样做,并学习它自己。
我的问题在这里的文档:https://developers.google.com/youtube/iframe_api_reference它告诉我为谷歌提供一个锚标记,根据你传递的内容来附加iFrame。
然而,我在服务器端有react,并使用web-pack将其编译到客户端,我的react组件目前看起来像:
import React from 'react';
import { Link } from 'react-router'
import classnames from 'classnames'
const videoId = 'XxVg_s8xAms';
export default React.createClass({
getInitialState: function() {
return {
YTid: videoId,
}
},
render() {
return (
<section className="youtubeComponent-wrapper">
<div id="youtubePlayerAnchor"></div>
</section>
)
}
})
我已经尝试将开发人员文档中的代码添加到客户端上的script
标签,但没有发生任何事情,控制台没有任何事情。
是否有任何资源或任何人可以指给我正确的方向,我该如何去处理这个
谢谢!
你可以这样创建一个React组件:
import { Component, PropTypes } from 'react'
let loadYT
export default class YouTube extends Component {
componentDidMount () {
if (!loadYT) {
loadYT = new Promise((resolve) => {
const tag = document.createElement('script')
tag.src = 'https://www.youtube.com/iframe_api'
const firstScriptTag = document.getElementsByTagName('script')[0]
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag)
window.onYouTubeIframeAPIReady = () => resolve(window.YT)
})
}
loadYT.then((YT) => {
this.player = new YT.Player(this.youtubePlayerAnchor, {
height: this.props.height || 390,
width: this.props.width || 640,
videoId: this.props.YTid,
events: {
onStateChange: this.onPlayerStateChange
}
})
})
}
onPlayerStateChange = (e) => {
if (typeof this.props.onStateChange === 'function') {
this.props.onStateChange(e)
}
}
render () {
return (
<section className='youtubeComponent-wrapper'>
<div ref={(r) => { this.youtubePlayerAnchor = r }}></div>
</section>
)
}
}
YouTube.propTypes = {
YTid: PropTypes.string.required,
width: PropTypes.number,
height: PropTypes.number,
onStateChange: PropTypes.func
}
相关文章:
- 防止Iframe窗体在新窗口中打开
- React重新渲染但未显示正确的组件
- 将样式表插入iframe
- React组件等待所需道具进行渲染
- 在Twitter上用ie9中的空白src访问iframe的contentWindow
- backbone.js无法渲染视图
- Webpack开发服务器和React服务器端渲染
- 在数据提取完成之前进行页面渲染
- 如何临时暂停浏览器渲染,然后恢复整个页面
- 动态渲染 .mht 文件,无需加载/iframe/嵌入
- 在 Firefox 中动态渲染 iFrame
- 为什么使用 ReactTestUtils 将 iframe 渲染到 jsdom 中不提供 contentWindow
- 如何直接从响应中将 html 和 css 渲染到 iframe 中
- React dangerouslySetInnerHTML 渲染 iframe youtube 嵌入自 props
- FB.ui在我的应用程序iFrame中渲染iFrame
- 检查iFrame是否开始渲染或通过Javascript加载
- 使用YouTubes JS API和Reactjs渲染iFrame视频
- 使用YouTube's iFrame播放器在iOS webview中渲染内联视频
- ASP.NET'框架javascript不允许我渲染原始HTML IFRAME
- 如何在iframe中显示渲染的Handlebars模板