首页 > 解决方案 > 如何将 React Hooks 与 video.js 一起使用?

问题描述

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

我的反应版本是 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 HooksuseRef而不是refs。任何指南都会有所帮助。

标签: javascriptreactjsreact-hooks

解决方案


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

推荐阅读