0

我有一个VideoItem- 和一个 -Player组件

VideoList单击按钮并进入全屏模式(按预期工作)单击全屏时,我将取消静音播放器。

如何将“静音”更改从VideoList传递 到Player?在我的Player我还有一个“取消静音”按钮(它也按预期工作:

这是我到目前为止所拥有的

视频项.jsx

import React, { useRef, useState, useEffect } from "react"
import { findDOMNode } from "react-dom"
import screenfull from "screenfull"
import VideoPlayer from "./VideoPlayer"

const VideoList = (videos) => {
  const ref = useRef()

  const toggleFullScreen = () => {
    screenfull.request(findDOMNode(ref.current))
  }

  const unMute = () => {
    console.log("Should pass Mute state to player", muted)
  }
  return (
   <>
     <VideoPlayer
            ref={ref}
            mute={muted}
            videoURL={videoUrl}
     />
     <a
       href="#"
       onClick={e => {
         e.preventDefault()
         unMute()
         toggleFullScreen()
       }}
     >
      Show Fullscreen
     </a>
  )
}

播放器.jsx

import React, { forwardRef, useState, useEffect } from "react"
import ReactPlayer from "react-player"
const VideoPlayer = forwardRef((props, ref, mute) => {
  let [muteState, setMuteState] = useState(true)

  return (
    <>
      <i className={`fal fa-volume-${muteState ? "up" : "mute"}`}
         onClick={() => {
           setMuteState(!muteState)
         }}
      />
      <ReactPlayer
          ref={ref}
          muted={muteState}
          loop={true}
          playing={true}
          url={props.videoURL}
        />
    </>
  )
}

谢谢!

4

1 回答 1

1

当您尝试从父级设置状态时,这通常表明您应该向上移动状态并使子级由父级控制:

const VideoList = (videos) => {
  const player = useRef();
  const [muted, setMuted] = useState(true);
  const [fullscreen, setFullscreen] = useState(false);

  const handleToggleMute = () => setMuted(current => !current);

  const handleFullscreen = event => {
    event.preventDefault();
    setMuted(false);
    setFullscreen(true);
  };

  return (
   <>
     <VideoPlayer
       ref={ref}
       muted={muted}
       fullscreen={fullscreen}
       videoURL={videoUrl}
       onToggleMute={handleToggleMute}
     />
     <a href="#" onClick={handleFullscreen}>Show Fullscreen</a>
  )
}

此外,我会useEffect与另一种状态一起使用,fullscreen以避免必须转发视频播放器的参考。

const VideoPlayer = ({videoURL, muted, fullscreen, onToggleMute}) => {
  const playerRef = useRef();

  useEffect(() => {
      if (fullscreen) {
        const videoElem = playerRef.current.getInternalPlayer();
        screenfull.request(videoElem);
      }
  }, [fullscreen]);

  return (
    <>
      <i 
        className={`fal fa-volume-${muted ? "up" : "mute"}`}
        onClick={onToggleMute}
      />
      <ReactPlayer
        ref={playerRef}
        muted={muted}
        loop={true}
        playing={true}
        url={videoURL}
      />
    </>
  )
}
于 2020-10-06T09:33:36.810 回答