【问题标题】:Cannot set properties of undefined (setting 'player') ReactPlayer无法设置未定义的属性(设置“播放器”)ReactPlayer
【发布时间】:2021-11-29 01:09:30
【问题描述】:

我一直尝试在 ReactPlayer 上使用 seekTo() 方法,但它一直告诉我 this 未定义。

function VideoPlayer({
  endVideo,
  timePlayed,
  controls,
  playing,
  videoDuration
}) {
  return (
    <div className="video-player">
      <ReactPlayer
        ref={(player) => {
          this.player = player;
        }}
        url="https://res.cloudinary.com/amarachi-2812/video/upload/v1630370229/videoplayback_1_pr2hzi.mp4"
        playing={playing}
        // playing={true}
        controls={controls}
        onStart={() => this.player.seekTo(timePlayed)}
        onEnded={endVideo}
      />
    </div>
  );
}

ReactPlayer error

【问题讨论】:

    标签: javascript reactjs react-player


    【解决方案1】:

    你为什么在箭头函数中使用它?

    试试这个:

    import React from "react";
    import ReactPlayer from "react-player";
    
    let player;
    
    export const VideoPlayer = ({
      endVideo,
      timePlayed,
      controls,
      playing,
      videoDuration
    }) => (
      <div className="video-player">
        <ReactPlayer
          ref={(ref) => {
            player = ref;
          }}
          url="https://res.cloudinary.com/amarachi-2812/video/upload/v1630370229/videoplayback_1_pr2hzi.mp4"
          playing={playing}
          // playing={true}
          controls={controls}
          onStart={() => player.seekTo(timePlayed)}
          onEnded={endVideo}
        />
      </div>
    );
    
    export const MemoizedVideoPlayer = React.memo(VideoPlayer);
    

    【讨论】:

      【解决方案2】:

      尝试,通过 useState 钩子设置实例。

      将处理程序包装在 useCallback 中以防止不必要的重新渲染,但如果它们出现,请不要忘记它们的依赖关系。

      不要忘记查看您正在使用的库的存储库,有时它会有所帮助。

      另外,我的建议是更详细地阅读函数。

      另外,我做了一些小改动。

      • 该组件名为视频播放器。 “videoDuration”的属性可以称为“duration”。这样会更正确,我们也不会迷失对转移属性的理解。
      • Url 将从 props 中获取。将源指向外部并重用组件。
      • 将“endVideo”属性重命名为“onEnded”。为清楚起见,也就是说,它将与我们转移到 react-player 的处理程序类似地命名

      开始吧!

      import React, { useState, useCallback } from "react";
      import ReactPlayer from "react-player";
      
      export const VideoPlayer = ({ url, onEnded, timePlayed, controls, playing, duration}) => {
       const [instance, setInstance] = useState(null);
      
       const handleStart = useCallback(() => {
           if (instance) {
               instance.seekTo(timePlayed)
           }
       }, [instance, timePlayed])
      
       return (
          <div className="video-player">
              <ReactPlayer
                  ref={setInstance}
                  url={url}
                  playing={playing}
                  controls={controls}
                  onStart={handleStart}
                  onEnded={onEnded}
              />
          </div>
      )};
      

      【讨论】:

        猜你喜欢
        • 2022-10-30
        • 2023-02-10
        • 2022-11-19
        • 2021-11-27
        • 1970-01-01
        • 2022-08-16
        • 2015-12-07
        • 2013-05-28
        相关资源
        最近更新 更多