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

时间:2019-02-23 01:52:45

标签: javascript reactjs react-hooks

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

我得到了错误

  

不变违反:功能组件不能具有引用。你是否   是要使用React.forwardRef()?

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

1 个答案:

答案 0 :(得分:1)

您正在将字符串传递给视频元素的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>
  );
}