You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在VS Code开发的React Web项目中使用JavaScript实现视频的暂停与播放?

How to Implement Video Play/Pause in a React Web Project (VS Code)

Great question! Implementing play/pause functionality for videos in React is straightforward once you leverage React's refs and state. Here's a step-by-step guide tailored for your VS Code setup:

1. Basic Setup with React Refs

To interact with the HTML video element directly, we'll use React's useRef hook—it lets us access the underlying DOM node without re-rendering the component.

First, create a new component (or add this to your existing one):

import React, { useRef, useState } from 'react';

const VideoPlayer = () => {
  // Ref to hold the video DOM element
  const videoRef = useRef(null);
  // State to track if the video is playing
  const [isPlaying, setIsPlaying] = useState(false);

  // Play/Pause handler function
  const handlePlayPause = () => {
    const video = videoRef.current;
    if (!video) return; // Guard clause if ref isn't attached yet

    // Toggle play/pause based on current state
    if (isPlaying) {
      video.pause();
    } else {
      video.play();
    }
    // Update state to reflect new status
    setIsPlaying(!isPlaying);
  };

  return (
    <div style={{ margin: '2rem' }}>
      <video
        ref={videoRef}
        width="640"
        height="360"
        // Remove the comment below if you want default browser controls too
        // controls
      >
        {/* Replace with your video path/URL */}
        <source src="/sample-video.mp4" type="video/mp4" />
        Your browser does not support the video tag.
      </video>
      <button 
        onClick={handlePlayPause} 
        style={{ marginTop: '1rem', padding: '0.5rem 1rem', fontSize: '1rem' }}
      >
        {isPlaying ? 'Pause' : 'Play'}
      </button>
    </div>
  );
};

export default VideoPlayer;

2. Key Details Explained

  • useRef: This hook creates a reference to the <video> element, allowing us to call native browser methods like play() and pause() directly.
  • useState: Tracks the play/pause status to update the button text dynamically—users will see "Pause" when playing and "Play" when paused.
  • handlePlayPause: The core logic that checks the current state of the video, triggers the corresponding action, and updates the component state.

3. Testing in VS Code

  1. Add your video: If you're using Create React App, place your video file in the public folder (so the src path works as /your-video.mp4). For other setups, adjust the path to match your project structure.
  2. Run the dev server: Open VS Code's terminal (Ctrl+`), then run:
    npm start
    # Or if using yarn:
    yarn start
    
  3. Test the functionality: Open your browser to http://localhost:3000 (default for Create React App) and click the play/pause button to verify it works.

Common Troubleshooting Tips

  • Video not loading? Double-check your src path. If using Create React App, assets in public are served from the root, so /video.mp4 is correct if the file is in public/video.mp4.
  • Autoplay blocked? Browsers block autoplay unless the user interacts with the page first—your play button click counts as a valid interaction, so this won't be an issue here.
  • Unsupported format? Stick to MP4 for broad browser compatibility; other formats like WebM may require fallback sources.

内容的提问来源于stack exchange,提问作者ANURUDH KUMAR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 11:32:28