【问题标题】:Play local videos in backgoung - REACT在后台播放本地视频 - REACT
【发布时间】:2021-09-23 18:43:29
【问题描述】:

我制作了一个包含 3 个本地视频的数组,我希望它们在主页上更改为背景,假设每 5 秒一次。我创建了一个数组,设置状态,当我 console.log 状态时,我看到控制台每 5 秒调用一个新视频,但在我的屏幕上只有第一个视频一直在循环。在返回视频源时,如果我对视频 [0]、[1] 或 [2] 进行硬编码,它将播放下一个视频。

这是我的代码:

let videoArray = [Miami, Miami2, Miami3];

function Home() {
const [videos, setVideos] = useState(videoArray);
const [currentVideo, setCurrentVideo] = useState(0);

//CHANGE VIDEOS FROM ARRAY EVERY 5 SECONDS
useEffect( () => {

const interval = setInterval(() => {   
  setCurrentVideo(currentVideo => (currentVideo+1)%videos.length)  
 }, 5000);
 return () => clearInterval(interval);
 }, [videos]);

return (
    
    <div id='home' className='home-div'> 
    <video autoPlay loop muted className="video">
        <source src={videos[currentVideo]} type='video/mp4' />
       </video> 

【问题讨论】:

    标签: reactjs video render


    【解决方案1】:

    好的,我想通了。它可能会在未来帮助某人。我想这不是最好的解决方案,但它可以满足我的需求。

    This function changes video onClick.
    
    function playVideo(source) {
    let video = document.getElementById('player');
    video.src= source;
    video.load();
    video.play();
    } 
    
    
    This function changes video every 12 secods.
    useEffect( () => {
    const interval = setInterval(() => {   
        setCurrentVideo(currentVideo => (currentVideo+1)%videos.length)
        let video = document.getElementById('player');
        video.src= videos[currentVideo];
        video.load();
        video.play();    
        // console.log(currentVideo)
    }, 12000);
    
    return () => clearInterval(interval); 
    }, [currentVideo]);
    
    
    
    
    <video id="player" autoPlay loop muted className="video">
            <source id="source1" src={videos[currentVideo]} type='video/mp4' />
           </video> 
           {/* <p style={{background:'red'}}>{videos[currentVideo]}</p> */}
           <div className='buttons'>
               <button src={Miami} id="video1" onClick={()=>playVideo(Miami)}></button>
               <button src={Miami2} id="video2" onClick={()=>playVideo(Miami2)}></button>
               <button src={Miami3} id="video3" onClick={()=>playVideo(Miami3)}></button>
           </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-13
      • 1970-01-01
      • 2015-03-02
      • 1970-01-01
      • 2020-07-02
      相关资源
      最近更新 更多