我尝试在 next.js 项目中配置 video.js,但它不起作用。
在加载开始时,播放器显示为黑色并突然消失。 控制台中有一条警告,内容如下:
“video.es.js?31bb:228 VIDEOJS:警告:提供的元素未包含在 DOM 中”
播放器组件代码如下:
import React from 'react';
import videojs from 'video.js';
import 'video.js/dist/video-js.css';
export const ThorPlayer = (props) => {
const videoRef = React.useRef(null);
const playerRef = React.useRef(null);
const {options, onReady} = props;
React.useEffect(() => {
// Make sure Video.js player is only initialized once
if (!playerRef.current) {
const videoElement = videoRef.current;
if (!videoElement) return;
const player = playerRef.current = videojs(videoElement, options, () => {
player.log('player is ready');
onReady && onReady(player);
});
// You can update player in the `else` block here, for example:
} else {
player.autoplay(options.autoplay);
player.src(options.sources);
}
}, [options, videoRef]);
// Dispose the Video.js player when the functional component unmounts
React.useEffect(() => {
const player = playerRef.current;
return () => {
if (player) {
player.dispose();
playerRef.current = null;
}
};
}, [playerRef]);
return (
<div data-vjs-player>
<video ref={videoRef} className='video-js vjs-big-play-centered' style={{ width: "800px", height:"400px" }}/>
</div>
);
}
export default ThorPlayer;
实现该组件的页面是这样的:
import React from 'react'
import ThorPlayer from '../../components/_ThorPlayer'
export default function index() {
const playerRef = React.useRef(null);
const videoJsOptions = {
autoplay: true,
controls: true,
responsive: true,
fluid: true,
sources: [{
src: 'https://obj-gravscale.zadarazios.com:443/v1/AUTH_f57eb386f52e4dc0bcdf19764aecc205/ct/bl_se.mp4',
type: 'video/mp4'
}]
};
const handlePlayerReady = (player) => {
playerRef.current = player;
// You can handle player events here, for example:
player.on('waiting', () => {
player.log('player is waiting');
});
player.on('dispose', () => {
player.log('player will dispose');
});
};
return (
<>
<h1>Teste de Player: </h1>
<ThorPlayer options={videoJsOptions} onReady={handlePlayerReady} />
<div></div>
</>
)
}
已经在 next.js 中实现了 video.js 的人可以帮我解决这个问题吗?
最佳答案
您是否使用过 React 18?我遇到了和你一样的问题,这是由 useEffect fires twice in development mode 引起的.
作为 video.js 7.20 发布之前的解决方法,您可以使用 technique described in this comment .
关于javascript - Video.js 无法在带有服务器端渲染的 next.js 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72788050/