VideoPlayer.tsx 1.3 KB

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