创建可以避免在React上复制youtube链接的视频播放器

问题描述 投票:0回答:1

我想创建一个在线学习网站,需要一个可以避免复制YouTube链接的视频播放器(我把视频放在YouTube上)。我找到了 1 个名为 medialement.js 的库,但我未能将其实现到 React 中。有谁知道解决方案吗?谢谢。

文档:medialement

import { MediaElementPlayer } from 'mediaelement';
import React, { useState } from 'react';
import 'mediaelement';


const VideoPlayers = () => {
  const [player, setPlayer] = useState(null);

  React.useEffect(() => {
    const options = {
      success: (media, node, instance) => {
        setPlayer(instance);
      },
      error: (media, node) => {
        console.error('Error loading media:', media);
      },
    };
    const player = new MediaElementPlayer('my-video', options);
    setPlayer(player);

  }, []);

  return (
    <div>
      {player && (
        <video
          id="my-video"
          width="640"
          height="480"
          controls
        >
          <source src="https://example.com/video.mp4" type="video/mp4" />
        </video>
      )}
    </div>
  );
};

export default VideoPlayers;

我尝试按照上面的方式创建一个组件,但出现错误

服务器错误 ReferenceError:元素未定义

reactjs video-streaming
1个回答
0
投票

您面临的问题

ReferenceError
。 这里

const player = new MediaElementPlayer('my-video', options);

您必须使用

useRef

传递引用,而不是直接使用 ID
import React, { useEffect, useRef } from 'react';
import { MediaElementPlayer } from 'mediaelement';

const VideoPlayers = () => {
  const videoRef = useRef(null);

  React.useEffect(() => {
    const options = {
      success: (media, node, instance) => {
        setPlayer(instance);
      },
      error: (media, node) => {
        console.error('Error loading media:', media);
      },
    };
    const player = new MediaElementPlayer(videoRef.current, options);
    setPlayer(player);

  }, []);

  return (
    <div>
      <video
        ref={videoRef}
        width="640"
        height="480"
        controls
      >
        <source src="https://example.com/video.mp4" type="video/mp4" />
      </video>
    </div>
  );
};

export default VideoPlayers;

此外,如果您想自动执行此操作,您可以直接从

MediaElement
react-mediaelement-wrapper
,它已经存在于您提供的文档中。

import React from 'react';
import { MediaElement } from 'react-mediaelement-wrapper';

const VideoPlayers = () => {
  return (
      <MediaElement
        id="my-video"
        width={640}
        height={480}
        controls
        sources={[
          {
            src: 'https://example.com/video.mp4',
            type: 'video/mp4',
          },
        ]}
      />
  );
};

export default VideoPlayers;

© www.soinside.com 2019 - 2024. All rights reserved.