简体   繁体   English

如何在video.js中使用React Hooks?

[英]How to use React Hooks with video.js?

I am using video.js in React. 我在React中使用video.js。 I try to migrate to React Hooks. 我尝试迁移到React Hooks。

My React version is 16.8.3 我的React版本是16.8.3

This is original working code: 这是原始的工作代码:

import React, { PureComponent } from 'react';
import videojs from 'video.js';

class VideoPlayer extends PureComponent {
  componentDidMount() {
    const { videoSrc } = this.props;
    const { playerRef } = this.refs;

    this.player = videojs(playerRef, { autoplay: true, muted: true }, () => {
      this.player.src(videoSrc);
    });
  }

  componentWillUnmount() {
    if (this.player) this.player.dispose()
  }

  render() {
    return (
      <div data-vjs-player>
        <video ref="playerRef" className="video-js vjs-16-9" playsInline />
      </div>
    );
  }
}

After adding React Hooks 添加React Hooks之后

import React, { useEffect, useRef } from 'react';
import videojs from 'video.js';

function VideoPlayer(props) {
  const { videoSrc } = props;
  const playerRef = useRef();

  useEffect(() => {
    const player = videojs(playerRef.current, { autoplay: true, muted: true }, () => {
      player.src(videoSrc);
    });

    return () => {
      player.dispose();
    };
  });

  return (
    <div data-vjs-player>
      <video ref="playerRef" className="video-js vjs-16-9" playsInline />
    </div>
  );
}

I got the error 我得到了错误

Invariant Violation: Function components cannot have refs. 不变违规:功能组件不能具有引用。 Did you mean to use React.forwardRef()? 您是要使用React.forwardRef()吗?

But I am using React Hooks useRef instead of refs actually. 但是我实际上使用的是React Hooks useRef而不是refs Any guide will be helpful. 任何指南都会有所帮助。

You are passing a string to the video element's ref prop. 您正在将字符串传递到视频元素的ref属性。 Give it the playerRef variable instead. 而是给它playerRef变量。

You can also give useEffect an empty array as second argument as you only want to run the effect after the initial render. 您还可以给useEffect一个空数组作为第二个参数,因为您只想在初始渲染后运行效果。

function VideoPlayer(props) {
  const { videoSrc } = props;
  const playerRef = useRef();

  useEffect(() => {
    const player = videojs(playerRef.current, { autoplay: true, muted: true }, () => {
      player.src(videoSrc);
    });

    return () => {
      player.dispose();
    };
  }, []);

  return (
    <div data-vjs-player>
      <video ref={playerRef} className="video-js vjs-16-9" playsInline />
    </div>
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM