使用React原生可以通过使用HTML5的video标签来播放视频。以下是一个示例代码,展示了如何在React中使用video标签来播放视频并在扁平列表中暂停其他视频:
import React, { useState } from 'react';
const VideoPlayer = ({ videoUrl, isPaused, onPause }) => {
const videoRef = React.createRef();
// 播放视频
const playVideo = () => {
videoRef.current.play();
};
// 暂停视频
const pauseVideo = () => {
videoRef.current.pause();
};
// 当视频播放状态改变时调用
const handleVideoStateChange = () => {
if (isPaused) {
pauseVideo();
} else {
playVideo();
}
};
return (
<video
ref={videoRef}
src={videoUrl}
controls
onPause={onPause}
onPlay={playVideo}
onPause={pauseVideo}
onEnded={pauseVideo}
/>
);
};
const VideoList = ({ videos }) => {
const [pausedVideo, setPausedVideo] = useState(null);
// 暂停其他视频
const pauseOtherVideos = (videoId) => {
setPausedVideo(videoId);
};
return (
<div>
{videos.map((video) => (
<div key={video.id}>
<h3>{video.title}</h3>
<VideoPlayer
videoUrl={video.url}
isPaused={pausedVideo !== video.id}
onPause={() => pauseOtherVideos(video.id)}
/>
</div>
))}
</div>
);
};
const App = () => {
const videos = [
{ id: 1, title: 'Video 1', url: 'video1.mp4' },
{ id: 2, title: 'Video 2', url: 'video2.mp4' },
{ id: 3, title: 'Video 3', url: 'video3.mp4' },
];
return (
<div>
<h2>Video List</h2>
<VideoList videos={videos} />
</div>
);
};
export default App;
在上面的代码中,我们定义了一个VideoPlayer
组件和一个VideoList
组件。VideoPlayer
组件接收一个视频URL、一个布尔值isPaused
和一个回调函数onPause
作为props。它使用video
标签来播放视频,并根据isPaused
的值来控制视频的播放和暂停。当视频播放状态改变时,会调用handleVideoStateChange
函数来处理暂停和播放视频。
VideoList
组件接收一个视频列表作为props,并使用map
函数来渲染每个视频的标题和VideoPlayer
组件。当某个视频的播放状态改变时,会调用pauseOtherVideos
函数来暂停其他视频。
最后,在App
组件中,我们定义了一个视频列表,并将其传递给VideoList
组件来展示视频列表。
这样,当你在扁平列表中点击某个视频的播放按钮时,其他视频会自动暂停。
领取专属 10元无门槛券
手把手带您无忧上云