Tridib Chatterjee Ответов: 1

Как воспроизвести/приостановить видео при прокрутке списка видео в reactjs


I got a child component called Video in my web app with a separate scrollbar enabled inside, where a list of video loads each taking the full height and width of the Video component. I need to trigger a pause of the current playing video when the user scrolls down to the next video and the next video should start playing immediately. And this should continue throughout the component. I'm using Intersection Observer API inside useEffect() but unable to achieve the functionality till now. My current function starts playing the videos on the list all at once. Is there any other way to achieve the feature? If not where am I going wrong??


Что я уже пробовал:

import React, { useRef, useState, useEffect } from "react";
import "./Video.css";
import VideoFooter from "./VideoFooter";
import VideoSidebar from "./VideoSidebar";

function Video({ url, likes, shares, messages, channel, description, song }) {

  const [playing, setPlaying] = useState(false);
  const videoRef = useRef(null);
                                      //NEED HELP OVER HERE
    useEffect(() => {
    let video = document.querySelector("video");
    let observer = new IntersectionObserver(
      (entry) => {
        if (entry.intersectionRatio != 0.5 && !playing) {
          videoRef.current.pause();
          setPlaying(true);
        } else if (playing) {
          videoRef.current.play();
          setPlaying(false);
        }
      },
      { threshold: 1 }
    );
    observer.observe(video);
  }, [playing]);

  const handleVideoPress = () => {
    if (playing) {
      videoRef.current.pause();
      setPlaying(false);
    } else {
      videoRef.current.play();
      setPlaying(true);
    }
  };

  return (
    <div className="video">
      <video
        onClick={handleVideoPress}
        className="video__player"
        loop
        ref={videoRef}
        src={url}
      ></video>
    </div>
  );
}

export default Video;