📅  最后修改于: 2023-12-03 15:08:47.377000             🧑  作者: Mango
在ReactJS中创建视频播放器可以通过使用HTML5的video标签以及React的事件处理来实现。下面我们将介绍如何创建一个基本的视频播放器组件。
首先,我们需要创建一个基本的视频组件,它将渲染一个video标签并设置视频源。在这个组件中,我们需要使用ref
属性来获取video元素,以便我们在控制播放时能够使用它。
import React, { useRef } from "react";
const VideoPlayer = ({ src }) => {
const videoRef = useRef(null);
return (
<video ref={videoRef} src={src}>
Your browser does not support the video tag.
</video>
);
};
export default VideoPlayer;
接下来,我们需要添加一些控制播放的按钮。我们将添加“播放”和“暂停”按钮,并使用React的状态管理来控制它们的可见性。
import React, { useState, useRef } from "react";
const VideoPlayer = ({ src }) => {
const videoRef = useRef(null);
const [playing, setPlaying] = useState(false);
const togglePlay = () => {
if (playing) {
videoRef.current?.pause();
} else {
videoRef.current?.play();
}
setPlaying(!playing);
};
const hideControls = () => {
setControls(false);
};
const showControls = () => {
setControls(true);
};
return (
<div onMouseEnter={showControls} onMouseLeave={hideControls}>
<video ref={videoRef} src={src}>
Your browser does not support the video tag.
</video>
{playing ? (
<button onClick={togglePlay}>Pause</button>
) : (
<button onClick={togglePlay}>Play</button>
)}
</div>
);
};
export default VideoPlayer;
最后,我们将添加一个进度条来显示视频的当前播放位置,并允许用户拖动它来控制视频的播放位置。
import React, { useState, useRef } from "react";
const VideoPlayer = ({ src }) => {
const videoRef = useRef(null);
const [playing, setPlaying] = useState(false);
const [currentTime, setCurrentTime] = useState(0);
const togglePlay = () => {
if (playing) {
videoRef.current?.pause();
} else {
videoRef.current?.play();
}
setPlaying(!playing);
};
const hideControls = () => {
setControls(false);
};
const showControls = () => {
setControls(true);
};
const updateTime = () => {
setCurrentTime(videoRef.current?.currentTime);
};
const seek = (e) => {
const percent = e.nativeEvent.offsetX / e.target.offsetWidth;
videoRef.current.currentTime = percent * videoRef.current.duration;
setCurrentTime(percent * videoRef.current.duration);
};
return (
<div onMouseEnter={showControls} onMouseLeave={hideControls}>
<video ref={videoRef} src={src} onTimeUpdate={updateTime}>
Your browser does not support the video tag.
</video>
{playing ? (
<button onClick={togglePlay}>Pause</button>
) : (
<button onClick={togglePlay}>Play</button>
)}
<div>
<progress
max={videoRef.current?.duration}
value={currentTime}
onClick={seek}
/>
<span>{currentTime.toFixed(2)}</span>
</div>
</div>
);
};
export default VideoPlayer;
现在我们已经完成了一个基本的视频播放器组件。我们还可以添加其他功能,如音量控制、全屏模式等,以使其更加完善。