我在React中使用video.js。我尝试迁移到React Hooks。
我的React版本是16.8.3
这是原始工作代码:
import React, { PureComponent } from 'react';
import videojs from 'video.js';
class VideoPlayer extends PureComponent {
componentDidMount() {
const { videoSrc } = this.props;
const { playerRef } = this.refs;
this.player = videojs(playerRef, { autoplay: true, muted: true }, () => {
this.player.src(videoSrc);
});
}
componentWillUnmount() {
if (this.player) this.player.dispose()
}
render() {
return (
<div data-vjs-player>
<video ref="playerRef" className="video-js vjs-16-9" playsInline />
</div>
);
}
}
添加React Hooks之后
import React, { useEffect, useRef } from 'react';
import videojs from 'video.js';
function VideoPlayer(props) {
const { videoSrc } = props;
const playerRef = useRef();
useEffect(() => {
const player = videojs(playerRef.current, { autoplay: true, muted: true }, () => {
player.src(videoSrc);
});
return () => {
player.dispose();
};
});
return (
<div data-vjs-player>
<video ref="playerRef" className="video-js vjs-16-9" playsInline />
</div>
);
}
我得到了错误
不变违反:功能组件不能具有引用。你是否 是要使用React.forwardRef()?
但是我实际上使用的是React Hooks useRef
而不是refs
。任何指南都会有所帮助。
答案 0 :(得分:1)
您正在将字符串传递给视频元素的ref
属性。改用playerRef
变量。
您也可以给useEffect
一个空数组作为第二个参数,因为您只想在初始渲染后运行效果。
function VideoPlayer(props) {
const { videoSrc } = props;
const playerRef = useRef();
useEffect(() => {
const player = videojs(playerRef.current, { autoplay: true, muted: true }, () => {
player.src(videoSrc);
});
return () => {
player.dispose();
};
}, []);
return (
<div data-vjs-player>
<video ref={playerRef} className="video-js vjs-16-9" playsInline />
</div>
);
}