React Создание элементарного Video компонента
Пробую создать элементарный <video>
элемент который бы автоматом запускал проигрывание видео после загрузки. Код выглядит следующим образом.
import React, {useRef, useEffect} from 'react';
import { createRoot } from 'react-dom/client';
import './index.css';
const VideoPlayer = ({src}) => {
const videoRef = useRef(null);
useEffect(() => {
const videoElement = videoRef.current;
if (videoElement) {
videoElement.addEventListener('ended', handleVideoEnded);
videoElement.play().catch((error) => {
console.log('Auto-play failed:', error);
});
}
return () => {
if (videoElement) {
videoElement.removeEventListener('ended', handleVideoEnded);
}
};
}, []);
const handleVideoEnded = () => {
if (videoRef.current) {
videoRef.current.play();
}
};
return (
<video width="100%" height="100%" controls className="video_block" ref={videoRef} autoPlay loop muted>
<source src={src} type="video/mp4"/>
</video>
);
};
class App extends React.Component {
render() {
let videoSource = '/videos/start_long_1024x1366.mp4';
return (
<div className="field">
<VideoPlayer src={videoSource}/>
</div>
);
}
}
const container = document.getElementById('root');
const root = createRoot(container);
root.render(<App />);
Видео файл находиться в директории static/videos/start_long_1024x1366.mp4
Но при монтировании, оно почему-то не отображается, а файл не отображает атрибут muted
Подскажите. что я делаю не так ?
Источник: Stack Overflow на русском