如何在ReactJS中使用youtube onPlay = {}函数?

问题描述

我安装了youtube-react API,并且您可以使用onPlay函数,但问题是加载视频<YouTube videoId={Projects.videoID} onPlay={autoplayChange} onPause={autoplayChange} onEnd={autoplayChange}/>的速度非常慢

如何使用带有youtube API的常规iframe重新创建类似的功能?我找不到任何有关将其实现到reactjs的文档。 https://developers.google.com/youtube/iframe_api_reference Google的API参考提到了onStateChange下的功能,但我无法弄清我认为此处有人可能对我的问题有所解答的实现。预先感谢。

解决方法

签出react-player,您可以使用npm快速安装它:

npm install react-player

速度快,可以让您对所需的onPlay功能进行很多控制。 git中的示例:

import React from 'react'
import ReactPlayer from 'react-player/lazy'

// Lazy load the YouTube player
<ReactPlayer url='https://www.youtube.com/watch?v=ysz5S6PUM-U' />

通过钩子,您可以像这样添加onPlay功能:

import React,{ useState } from 'react'
import ReactPlayer from 'react-player/lazy'

const MyPlayer = () => {

    const [ playState,setPlayState ] = useState(false);

    const yourFunction = (event) => {

        console.log('Your event: ',event);

    };

    return (
        <ReactPlayer 
            url='https://www.youtube.com/watch?v=ysz5S6PUM-U'
            playing={playState}
            onPlay={yourFunction}/>
    );

}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...