video-play.tsx
1.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import React, {useEffect, useRef, useState} from 'react';
type VideoPlayProps = {
key: string;
url: string;
className: string;
};
// 视频自动播放组件
const VideoPlay: React.FC<VideoPlayProps> = (props) => {
const videoRef = useRef<HTMLVideoElement>(null);
const [isPlaying, setIsPlaying] = useState(true);
useEffect(() => {
if (videoRef.current) {
videoRef.current.onended = () => {
setIsPlaying(true);
};
}
}, [props?.key]);
useEffect(() => {
if (isPlaying && videoRef.current) {
videoRef.current.play().catch(() => {
setIsPlaying(false);
});
}
}, [isPlaying]);
return (
<>
{
props?.url ? <video
id={props?.url}
ref={videoRef}
autoPlay
loop
muted
playsInline
className={`${props?.className}`}
>
<source src={props?.url} type="video/mp4" />
</video> : ''
}
</>
);
};
export default VideoPlay;