在 React js 中更改幻灯片时暂停视频?

Pause video when changing slide in react js?

我有一个使用 react slick slider 的简单滑块 我的一张幻灯片是使用 react player 的视频,现在我想如果用户更改幻灯片以暂停播放视频,这就是我目前所拥有的。

这是代码沙箱的现场演示:pause video demo

Player.js.

import React, { useState } from "react"
import ReactPlayer from "react-player"

function Player({ isPlaying, setIsPlaying }) {
  const handleisPlaying = () => {
    console.log("before playing?", isPlaying);
    setIsPlaying(false);
    console.log("after playing?", isPlaying);
  };
  return (
    <div>
      <ReactPlayer
        url="https://www.youtube.com/watch?v=5DjF0C3dybg"
        playing={isPlaying}
        volume={1}
        width="50vw"
        height="50vh"
      />
      <button
        type="button"
        className="btn btn-success"
        onClick={handleisPlaying}
      >
        pause
      </button>
    </div>
  );
}

export default Player;

这是滑块代码。

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

export default function APP() {
  const [isPlaying, setIsPlaying] = useState(false);
  const settings = {
    dots: true,
    beforeChange: () => {
      console.log("after change");
      setIsPlaying(false);
    }
  };

  return (
    <div className="container">
      <Slider {...settings}>
        <div>
          <img src="http://placekitten.com/g/400/200" />
        </div>
        <div>
          <img src="http://placekitten.com/g/400/200" />
        </div>
        <Player setIsPlaying={setIsPlaying} isPlaying={isPlaying} />
      </Slider>
    </div>
  );
}

反应光滑的滑块文档 react slick docs

我需要做什么才能让它正常工作?

您没有在视频开始时将 isPlaying 设置为 true

这里是你如何做到的。

 <ReactPlayer
        url="https://www.youtube.com/watch?v=5DjF0C3dybg"
        playing={isPlaying}
        onStart={() => setIsPlaying(true)}
        onPause={() => setIsPlaying(false)}
        onEnded={() => setIsPlaying(false)}
        volume={1}
        width="50vw"
        height="50vh"
      />

你也可以在这里查看。 https://codesandbox.io/s/pause-de-video-forked-9788g?file=/src/Player.js

@saksh 的回答如果您暂停视频并再次继续播放将无效。我从 react-player 库的维护者的评论中得到以下内容:https://github.com/cookpete/react-player/issues/1152#issuecomment-767666288

 <ReactPlayer
        url="https://www.youtube.com/watch?v=5DjF0C3dybg"
        playing={isPlaying}
        onPlay={() => setIsPlaying(true)}
        onPause={() => setIsPlaying(false)}
        volume={1}
        width="50vw"
        height="50vh"
      />

https://codesandbox.io/s/pause-de-video-forked-qb685?file=/src/Player.js