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

后端 未结 5 1015

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:34

    This answer adds to @mheavers, which I upvoted.

    There are a few differences:

    • One can pass noControls as a prop to the Video component, and apply the click event only if the doesn't have the default controls (which will be the case when noControls is passed).
    • The handler function is a toggler; enabling one to play or pause according to its current state.
    • One can create a play button overlay style through the class video__play-button, whilst the same handler hides it through the class is-playing.
    • It also shows how to use two or more ref and pass them as a parameter to a pure render function.
    import React, { useRef } from 'react';
    import PropTypes from 'prop-types';
    
    const renderVideo = ({
      noControls,
      src,
      vidButtonRef,
      vidRef,
      handleToggleVideo,
    }) => (
      <>
        {noControls ? (
          
    ) : ( )} ); const Video = props => { const vidRef = useRef(null); const vidButtonRef = useRef(null); const { noControls, src } = props; const handlePlay = () => { vidRef.current.play(); // hide overlay play button styles, set by 'video__play-button' vidButtonRef.current.classList.add('is-playing'); }; const handlePause = () => { vidRef.current.pause(); // show overlay play button styles, set by 'video__play-button' vidButtonRef.current.classList.remove('is-playing'); }; const handleToggleVideo = () => (vidRef.current.paused ? handlePlay() : handlePause()); return ( <> {renderVideo({ noControls, src, vidButtonRef, vidRef, handleToggleVideo, })} ); }; Video.propTypes = { noControls: PropTypes.bool, videoUrl: PropTypes.string, }; export default Video;

提交回复
热议问题