首页 > 解决方案 > 提取状态下 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;

标签: javascriptreactjsyoutubeevent-handling

解决方案


'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”


推荐阅读