video.js 如何使用 React Hooks?

How to use React Hooks with video.js?

我在 React 中使用 video.js。我尝试迁移到 React Hooks。

我的 React 版本是 16.8.3

这是原始工作代码:

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>
    );
  }
}

添加 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>
  );
}

我收到错误消息

Invariant Violation: Function components cannot have refs. Did you mean to use React.forwardRef()?

但实际上我使用的是 React Hooks useRef 而不是 refs。任何指南都会有所帮助。

您正在将字符串传递给视频元素的 ref 属性。改为给它 playerRef 变量。

您还可以给 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>
  );
}