React Hooks 视频滑块,视频未播放

时间:2021-03-29 17:11:47

标签: javascript reactjs react-hooks html5-video use-state

我正在尝试在我的 React 项目中制作一个视频滑块,当我检查组件时,我看到了我的视频,如下面的屏幕截图所示:

enter image description here

但它没有播放,并且控件处于非活动状态。

我做错了什么?

这是我的代码


import React, { useState } from 'react'

const Slider = () => {

    const [ videos, setVideos] = useState([
       'https://www.youtube.com/watch?v=PFPfxcvRshk',
       'https://www.youtube.com/watch?v=Lst9mgmOnbo',
       'https://www.youtube.com/watch?v=bnzVL0a5h5w',
    ]);

    const [currentVideoIndex, setCurrentVideoIndex] = useState(0);

    const prevSlide = () => {
    
    // check if current video  equals 0 

    const startFromBeginning = currentVideoIndex === 0;

    const index = startFromBeginning ? videos.length - 1 : currentVideoIndex - 1;

    // assign the logical index to current video that will render 

    setCurrentVideoIndex(index)

    }

    const nextSlide = () => {
        // check if we need to start over from the first index
        const resetIndex = currentVideoIndex === videos.length - 1;
    
        const index = resetIndex ? 0 : currentVideoIndex + 1;
    
        // assign the logical index to current video index that will be used in render method
        setCurrentVideoIndex(index);
      }


    // create a new array with 1 element from the source video
    const firstVideoSlide = videos.slice( currentVideoIndex, currentVideoIndex + 1)

    // check the length of the new array
    const videoSourceToDisplay = firstVideoSlide.length < 1

    // if  the imageSourcesToDisplay's length is lower than 5 images than append missing images from the beginning of the original array

    ? [...firstVideoSlide, ...videos.slice(0, 1 - firstVideoSlide.length) ]
    : firstVideoSlide;



    return (
        <div>
            
       <button onClick={prevSlide}>prev</button>

          <div className="media-content flex justify-center ">
             <div className="media-content flex justify-center border-4 border-light-blue-500 border-opacity-25 shadow-md">
               
                    {
                    videoSourceToDisplay.map((video, index) => 

                    <video controls loop className="videocard">
                        <source src={video} key={index} type="video/mp4" />
                    </video>

                    )}
              </div>
            </div>

      <button onClick={nextSlide}>next</button>
        </div>
    )
}

export default Slider

0 个答案:

没有答案