简体   繁体   English

如何在 reactJS 中使用 onClick 为多个视频播放 HTML5 视频?

[英]How to play HTML5 video with onClick in reactJS for multiple videos?

In my react component I have added video tag like:在我的反应组件中,我添加了视频标签,如:

<video controls ref="video">
  <source src="VIDEO SOURCE" type="video/mp4" />
</video>

And I have added play button like:我添加了播放按钮,如:

<button onClick={() => {this.refs.video.play()}}>Play Button</button>

This code is working for single video when using ref使用ref时,此代码适用于单个视频

But i have multiple video in one page so但是我在一页中有多个视频所以

How to use multiple ref in loop?如何在循环中使用多个引用?

instead of using ref use mapping function of videos and pass video uri to onplay button something like this而不是使用 ref 使用视频的映射功能并将视频 uri 传递给像这样的播放按钮

const [videoURI,setVideoURL] = useState(null)
const _onplayvideo= (video_uri) =>{
setVideoURL(video_uri)
}
 ....
map((res)=>{
return(
 <>
 <Video uri={videoURI} />
 <Button onClick={()=>{_onplayvideo(res.video_uri)}} />
 </>
)
})

It would Work I guess.我猜它会起作用。 Check That检查那个

 const [AutoPlay, setAutoPlay] = useState({});

 const onClickHandler = id => {
   if (AutoPlay.hasOwnProperty(id)) {
     if (AutoPlay[id] === true) {
      setAutoPlay({...AutoPlay,[id]:false});    
  } else {
    setAutoPlay({...AutoPlay,[id]:true});
  }
} else {
  setAutoPlay({...AutoPlay,[id]:true});
}
}

return(
<>
 {

   Videos &&  Videos.map((result,index)=>{                                                  
     return(
            <>
            <video controls key={index} autoplay={AutoPlay[index]===true}>
            <source 
            src={result.Source} //Whatever The Source is
            type="video/mp4" />
            </video>
           <button onClick={() => onClickHandler(index)}>Play</button>
           </>
          )
          })

 }

</>

 )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM