如何在 ReactJS 中一个接一个地播放 2 个视频?
How to play 2 videos one after the other in ReactJS?
我只想播放一次介绍视频,然后再播放另一个循环播放的视频。我有这段代码可以检测第一个视频何时结束,但如何加载第二个视频并将其设置为循环播放?
const vidIndex = 0;
const videos = [videoIntro, videoLoop];
return (
<div className="main">
<video src = {videos[vidIndex]} autoPlay muted onEnded={() => vidIndex++} />
</div>
);
谢谢。
您可以简单地使用 useState
来跟踪视频索引。 CodeSandbox
import { useEffect, useState, useRef } from "react";
const videoIntro = "https://www.w3schools.com/tags/movie.mp4";
const videoLoop =
"https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4";
function App() {
const [vidIndex, setVidIndex] = useState(0);
const ref = useRef(null);
useEffect(() => {
if (vidIndex === 0 && ref.current) {
ref.current.play();
}
}, [ref, vidIndex]);
return (
<div className="main">
<video
style={{ display: vidIndex === 1 ? "none" : "block" }}
src={videoIntro}
autoPlay
muted
onEnded={() => setVidIndex((idx) => idx + 1)}
/>
<video
style={{ display: vidIndex === 0 ? "none" : "block" }}
src={videoLoop}
muted
loop
ref={ref}
/>
</div>
);
}
我只想播放一次介绍视频,然后再播放另一个循环播放的视频。我有这段代码可以检测第一个视频何时结束,但如何加载第二个视频并将其设置为循环播放?
const vidIndex = 0;
const videos = [videoIntro, videoLoop];
return (
<div className="main">
<video src = {videos[vidIndex]} autoPlay muted onEnded={() => vidIndex++} />
</div>
);
谢谢。
您可以简单地使用 useState
来跟踪视频索引。 CodeSandbox
import { useEffect, useState, useRef } from "react";
const videoIntro = "https://www.w3schools.com/tags/movie.mp4";
const videoLoop =
"https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4";
function App() {
const [vidIndex, setVidIndex] = useState(0);
const ref = useRef(null);
useEffect(() => {
if (vidIndex === 0 && ref.current) {
ref.current.play();
}
}, [ref, vidIndex]);
return (
<div className="main">
<video
style={{ display: vidIndex === 1 ? "none" : "block" }}
src={videoIntro}
autoPlay
muted
onEnded={() => setVidIndex((idx) => idx + 1)}
/>
<video
style={{ display: vidIndex === 0 ? "none" : "block" }}
src={videoLoop}
muted
loop
ref={ref}
/>
</div>
);
}