简体   繁体   中英

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

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

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>
           </>
          )
          })

 }

</>

 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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