首页 > 文章列表 > React 基础知识~useRef/ 视频播放

React 基础知识~useRef/ 视频播放

337 2024-11-14
  • useref 是跟踪 dom 元素状态的 react hook 之一。

  • 我们还可以使用这个钩子来控制 dom 元素的状态。

・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;

・我们将 useref 的值设置为 videoref 到视频元素的 ref 属性。

・当我们按下按钮时,我们可以使用按钮的 onclick 函数中的 videoref.current.pause() 或 videoref.current.play() 来控制视频动作。

・这是一个玩耍动作。

React 基础知识~useRef/ 视频播放

・这是一个停止动作。

React 基础知识~useRef/ 视频播放

抱歉,我无法以视频形式显示该动作。

来源:https://dev.to/kkr0423/react-basicsuseref-video-playing-5g5

本类最新

查看更多