how to play/pause video in React without external library?

后端 未结 5 1022

I have a video tag () in my webpage, and a \"play/pause\" button that when the user clicks on it, the video starts/stops playing . How can I do so in react if I\'m not allowed t

5条回答
  •  花落未央
    2021-02-14 00:51

    The most straightforward way would be to use refs which is a React feature that will let you invoke methods on the component instances that you have returned from a render().

    You can read up a little more on them in the docs: https://facebook.github.io/react/docs/more-about-refs.html

    In this case just add a ref string to your video tag like so:

    
    

    That way when you add click handlers to your buttons:

    
    

    The playVideo method will have access to your video reference through refs:

    playVideo() {
      this.refs.vidRef.play();
    }
    

    Here is a working DEMO so you can check out a full example.

提交回复
热议问题