【问题标题】:Pause Video When Not In Sight in React在 React 中看不到时暂停视频
【发布时间】:2021-06-28 07:17:18
【问题描述】:

我无法在视频未显示时暂停视频。切换到不同的滑块时,我已成功暂停它。 我还需要卸载或者如何防止它在不播放时在后台运行,所以它可能不会加载浏览器。

请在此处检查我的代码框 CLICK HERE

  useEffect(() => {
    const options = {
      root: document.querySelector("#video"),
      threshold: 0.1
    };
    observerRef.current = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.intersectionRatio !== 1) {
          setPlayed(false);
        }
      });
    }, options);
  }, []);

【问题讨论】:

    标签: javascript html reactjs react-hooks html5-video


    【解决方案1】:

    Click here 检查我已修复您的代码,现在视频在看不见时暂停。 只是添加了一个钩子来检查玩家是否在 dom 中并根据此管理状态

    const isVisible = useOnScreen(videoRef);
    
      useEffect(() => {
        setPlayed(isVisible);
      }, [isVisible]);
    
     <div ref={videoRef}  className="react-player-wrapper">
          <ReactPlayer
            playsinline={true}
            playing={played}
            ....
             
            light={    "https://pbs.twimg.com/profile_images/875749462957670400/T0lwiBK8_400x400.jpg"
            }
          />
    

    用于检查玩家是否可见的钩子

     import React,{useEffect, useState} from "react";
        export default function useOnScreen(ref) {
          const [isIntersecting, setIntersecting] = useState(false)
          const observer = new IntersectionObserver(
            ([entry]) => setIntersecting(entry.isIntersecting)
          )
    
          useEffect(() => {
                observer.observe(ref.current)
            return () => { observer.disconnect() }
          }, [])
        
          return isIntersecting
        }
    

    【讨论】:

    • 它有错误。请再次检查。在“IntersectionObserver”上执行“观察”失败:参数 1 不是“元素”类型。
    • 请提供在不依赖外部链接的情况下理解您的答案所需的代码更改。
    • 确保您提供 ReactPlayer 外部 div 的 ref,而不是反应导致错误的播放器,并且我的代码框工作正常
    • @Abhi。请检查您的密码框codesandbox.io/s/video-player-with-slider-forked-5th85?file=/…。这里有错误
    • 现在检查我忘记在沙盒中保存代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多