React - useRef 没有暂停视频

React - useRef is not pausing video

我正在为滑块使用 react-slick。我想在幻灯片更改时停止视频。我为此使用 useRef,但播放或暂停功能不起作用。我该如何解决?

import React, { useRef } from "react";
import Slider from "react-slick";
import "slick-carousel/slick/slick.css";
import "slick-carousel/slick/slick-theme.css";
import "./styles.css";

export default function App() {
  const videoRef = useRef<HTMLVideoElement>(null);

  const slideAfterChange = (current: number) => {
   console.log("after change", current);
   console.log("video ref", videoRef);
   videoRef.current?.pause();
 };

 const sliderSettings = {
   dots: true,
   infinite: true,
   autoplay: true,
   autoplaySpeed: 3000,
   speed: 1000,
   slidesToShow: 1,
   slidesToScroll: 1,
   afterChange: (currentSlide: number) => slideAfterChange(currentSlide)
 };

 return (
   <div className="App">
      <h1>Slider</h1>
      <Slider {...sliderSettings}>
       <div>
         <video ref={videoRef} controls width="100%" height="100%">
           <source
             src={
               "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4"
             }
           ></source>
         </video>
       </div>
       <div>
         <img src="http://placekitten.com/g/400/200" />
       </div>
     </Slider>
   </div>
 );
}

你可以在codesandbox上看到 https://codesandbox.io/s/reverent-swirles-m6bw1?file=/src/App.tsx

您可以向视频播放器添加一个 ID,然后使用 getElementById,而不是 useRef。

const slideAfterChange = () => {
    document.getElementById("videoPlayer")?.pause();
};
...
<video id="videoPlayer" controls width="100%" height="100%">