javascript - 提取状态下 react-youtube 的播放功能以在按钮 oncluck 中使用导致 CORS
问题描述
我在我的反应项目中使用来自 npm 的react-youtube库。我想在按钮 onClick 事件上播放和暂停 YouTube 视频。
我尝试将事件和函数从 YouTube 组件中提取到状态,然后通过按钮 onClick 调用该函数,但它导致跨源错误“未捕获的错误:引发了跨源错误。React 没有访问权限到开发中的实际错误对象。有关更多信息,请参阅https://reactjs.org/link/crossorigin-error。
我究竟做错了什么?以及如何从另一个组件(如按钮)触发 YouTube 组件事件?
import './App.css';
import YouTube from 'react-youtube';
import React, { Component } from 'react';
class App extends Component {
constructor(props){
super(props);
this.state = {
playerPlayVideo: () => {}
}
this.videoOnReady = this.videoOnReady.bind(this);
}
videoOnReady(event) {
// access to player in all event handlers via event.target
this.setState({
playerPlayVideo: event.target.playVideo
});
}
render() {
const opts = {
height: '390',
width: '640',
};
return (
<div>
<YouTube videoId="2g811Eo7K8U" opts={opts} onReady={this.videoOnReady} />
<button onClick={this.state.playerPlayVideo}>play</button>
</div>
);
}
}
export default App;
解决方案
'react-youtube' 在内部使用 YouTube Api。玩家执行的动作基于event.target
. 您正在将回调函数 playVideo 保存在一个状态中,这可能会导致范围问题。
在这种情况下,您可以简单地将 event.target 对象存储在 state 中,而不是将“playVideo”函数存储在 state 中。
this.state = {
playerPlayVideo: {},
};
然后单击按钮,您可以像这样简单地调用 playVideo,
<button onClick={() => this.state.playerPlayVideo.playVideo()}>
play
</button>
这行得通!我已经测试过了。
然后,您也可以通过切换状态逻辑来改善这一点,因为您现在event.target
直接存储在状态中。因此,您现在可以同时调用“playVideo”和“pauseVideo”
推荐阅读
- javascript - 当我旋转它时,如何将图像保持在模态体内部或内部?
- reactjs - 将带有参数的 onClick 分配给地图函数 React 内部的组件
- neuron-simulator - 在神经元上没有这样的文件或目录?
- reactjs - reactJS中不同用户的不同视图
- python - 如何将 .docx 文件保存到 S3 中?
- python - 尝试将小数点添加到浮点数时出现键错误
- bash - 替换文件名中模式的最短匹配
- mysql - 不能使用有 sum 或有 count mysql 5.7
- java - Spring webclient如何多次提取响应主体
- python-3.x - 如何使用exchangelib库python在电子邮件正文中嵌入图像