react实现视频
React 实现视频播放功能
在 React 中实现视频播放功能可以通过多种方式完成,以下是几种常见的方法:
使用 HTML5 <video> 标签
HTML5 提供了原生的 <video> 标签,可以直接在 React 组件中使用:
import React from 'react';
function VideoPlayer() {
return (
<div>
<video width="640" height="360" controls>
<source src="video.mp4" type="video/mp4" />
Your browser does not support the video tag.
</video>
</div>
);
}
export default VideoPlayer;
使用第三方库
如果需要更高级的功能(如自定义控件、播放列表等),可以使用第三方库如 react-player:

import React from 'react';
import ReactPlayer from 'react-player';
function VideoPlayer() {
return (
<div>
<ReactPlayer
url="https://example.com/video.mp4"
controls
width="640px"
height="360px"
/>
</div>
);
}
export default VideoPlayer;
实现自定义视频播放器
可以通过 React 状态和事件处理来自定义视频播放器:
import React, { useRef, useState } from 'react';
function CustomVideoPlayer() {
const videoRef = useRef(null);
const [isPlaying, setIsPlaying] = useState(false);
const togglePlay = () => {
if (isPlaying) {
videoRef.current.pause();
} else {
videoRef.current.play();
}
setIsPlaying(!isPlaying);
};
return (
<div>
<video
ref={videoRef}
width="640"
height="360"
src="video.mp4"
/>
<button onClick={togglePlay}>
{isPlaying ? 'Pause' : 'Play'}
</button>
</div>
);
}
export default CustomVideoPlayer;
处理视频源动态加载
如果需要动态加载视频源,可以通过 props 或状态传递:

import React, { useState } from 'react';
function DynamicVideoPlayer() {
const [videoUrl, setVideoUrl] = useState('video1.mp4');
return (
<div>
<video width="640" height="360" controls>
<source src={videoUrl} type="video/mp4" />
</video>
<button onClick={() => setVideoUrl('video2.mp4')}>
Change Video
</button>
</div>
);
}
export default DynamicVideoPlayer;
添加字幕和轨道
可以通过 <track> 标签为视频添加字幕:
<video width="640" height="360" controls>
<source src="video.mp4" type="video/mp4" />
<track
src="subtitles.vtt"
kind="subtitles"
srcLang="en"
label="English"
/>
</video>
响应式视频播放器
使用 CSS 确保视频播放器适应不同屏幕尺寸:
<div style={{ maxWidth: '100%', height: 'auto' }}>
<video style={{ width: '100%' }} controls>
<source src="video.mp4" type="video/mp4" />
</video>
</div>






