VideoPlayer.tsx 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { useRef, useEffect } from "react";
  2. import players from "video.js";
  3. interface IProps {
  4. options: players.PlayerOptions;
  5. onReady: (player: players.Player) => void;
  6. }
  7. const Widget = ({ options, onReady }: IProps) => {
  8. const videoRef = useRef<HTMLDivElement>(null);
  9. const playerRef = useRef<players.Player | null>();
  10. useEffect(() => {
  11. if (!playerRef.current) {
  12. const videoElement = document.createElement("video-js");
  13. videoElement.classList.add("vjs-big-play-centered");
  14. if (videoRef.current) {
  15. videoRef.current.appendChild(videoElement);
  16. }
  17. const player = (playerRef.current = players(videoElement, options, () => {
  18. onReady && onReady(player);
  19. }));
  20. } else {
  21. const player = playerRef.current;
  22. if (options.autoplay !== undefined) {
  23. player.autoplay(options.autoplay);
  24. }
  25. if (options.sources !== undefined) {
  26. player.src(options.sources);
  27. }
  28. }
  29. }, [options, playerRef, videoRef, onReady]);
  30. useEffect(() => {
  31. const player = playerRef.current;
  32. return () => {
  33. if (player && !player.isDisposed()) {
  34. player.dispose();
  35. playerRef.current = null;
  36. }
  37. };
  38. }, [playerRef]);
  39. return (
  40. <div data-vjs-player>
  41. <div ref={videoRef} className="video-js" />
  42. </div>
  43. );
  44. };
  45. export default Widget;