video-play.tsx 1.18 KB
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;