首頁  >  文章  >  web前端  >  React 基礎~useRef/ 影片播放

React 基礎~useRef/ 影片播放

DDD
DDD原創
2024-10-11 18:39:02308瀏覽
  • The useRef is one of the react hooks that tracks the state of DOM elements.

  • We can also control the state of DOM elements using this hook.

・src/Example.js

import { useRef, useState } from "react";

const Video = () => {
  const [playing, setPlaying] = useState();
  const videoRef = useRef();

  return (
    <div>
      <video style={{ maxWidth: "100%" }} ref={videoRef}>
        <source src="./sample.mp4"></source>
      </video>
      <button
        onClick={() => {
          if (playing) {
            videoRef.current.pause();
          } else {
            videoRef.current.play();
          }
          setPlaying((prev) => !prev);
        }}
      >
        {playing ? "Stop" : "Play"}
      </button>
    </div>
  );
};

const Example = () => {
  return (
    <>
      <Video />
    </>
  );
};

export default Example;

・We set a value of useRef as videoRef to the video element's ref attribute.

・When we press the button, we can control the video action using videoRef.current.pause() or videoRef.current.play() in the button's onClick function.

・This is a playing action.

React Basics~useRef/ video playing

・This is a stopping action.

React Basics~useRef/ video playing

Sorry I can't show the action as video.

以上是React 基礎~useRef/ 影片播放的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn