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/ 视频播放的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号