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

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

Hey there! Since you're building a React web project in VS Code, let's walk through exactly how to add play/pause functionality for videos using JavaScript. I'll share practical, React-friendly code snippets you can test right away.

Implementing Video Play/Pause in React

The cleanest way to handle video playback in modern React is with useRef (to access the video DOM element) and useState (to track whether the video is playing). Here's a complete, ready-to-use component:

import { useRef, useState } from 'react';

function VideoPlayer() {
  // Create a ref to access the <video> element directly
  const videoRef = useRef(null);
  // Track the current play state
  const [isPlaying, setIsPlaying] = useState(false);

  // Toggle play/pause when the button is clicked
  const togglePlayPause = () => {
    const videoElement = videoRef.current;
    if (!videoElement) return;

    if (isPlaying) {
      videoElement.pause();
    } else {
      videoElement.play();
    }
    // Flip the play state
    setIsPlaying(!isPlaying);
  };

  return (
    <div className="video-container">
      <video 
        ref={videoRef} 
        width="640" 
        height="360"
        // Sync state if user uses browser's default controls
        onPlay={() => setIsPlaying(true)}
        onPause={() => setIsPlaying(false)}
      >
        <source src="/your-video-file.mp4" type="video/mp4" />
        Your browser doesn't support HTML5 video.
      </video>
      {/* Dynamic button text based on play state */}
      <button onClick={togglePlayPause} style={{ marginTop: '10px' }}>
        {isPlaying ? '⏸️ Pause' : '▶️ Play'}
      </button>
    </div>
  );
}

export default VideoPlayer;

Quick Notes:

  • useRef lets us interact with the native <video> element's methods (play() and pause() are built into HTML5 video).
  • We added onPlay and onPause listeners to the video tag to keep our React state in sync if the user uses the browser's default video controls (like clicking directly on the video).
  • Place your video file in the public folder of your React project so the path /your-video-file.mp4 works correctly.

For Class Components (If You're Not Using Hooks)

If you're working with an older React class component, here's how to implement the same functionality:

import React, { Component } from 'react';

class VideoPlayer extends Component {
  constructor(props) {
    super(props);
    this.videoRef = React.createRef();
    this.state = { isPlaying: false };
  }

  togglePlayPause = () => {
    const videoElement = this.videoRef.current;
    if (!videoElement) return;

    this.state.isPlaying ? videoElement.pause() : videoElement.play();
    this.setState(prevState => ({ isPlaying: !prevState.isPlaying }));
  };

  // Sync state with browser controls
  handlePlay = () => this.setState({ isPlaying: true });
  handlePause = () => this.setState({ isPlaying: false });

  render() {
    return (
      <div className="video-container">
        <video 
          ref={this.videoRef} 
          width="640" 
          height="360"
          onPlay={this.handlePlay}
          onPause={this.handlePause}
        >
          <source src="/your-video-file.mp4" type="video/mp4" />
          Your browser doesn't support HTML5 video.
        </video>
        <button onClick={this.togglePlayPause} style={{ marginTop: '10px' }}>
          {this.state.isPlaying ? '⏸️ Pause' : '▶️ Play'}
        </button>
      </div>
    );
  }
}

export default VideoPlayer;

Troubleshooting Tips:

  • Autoplay Blocked? Most browsers block video autoplay unless the user interacts with the page first. Our button requires a user click, so this won't be an issue here.
  • Video Not Loading? Double-check your file path. Local videos need to be in the public folder, not src.
  • Third-Party Libraries? If you're using something like react-player, the API will have its own play/pause methods, but the core idea of tracking state and triggering actions stays the same.

内容的提问来源于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 10:02:40