Как использовать React Hooks с video.js? - PullRequest
0 голосов
/ 23 февраля 2019

Я использую video.js в React.Я пытаюсь перейти на 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 голосов
/ 23 февраля 2019

Вы передаете строку в ref prop видеоэлемента.Вместо этого присвойте ей переменную 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>
  );
}
...