Hon*_*iao 7 javascript reactjs react-hooks
我在 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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
添加 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>
);
}
Run Code Online (Sandbox Code Playgroud)
我得到了错误
不变违规:函数组件不能有引用。你的意思是使用 React.forwardRef() 吗?
但我实际上使用的是 React HooksuseRef而不是refs。任何指南都会有所帮助。
Tho*_*lle 18
您正在将字符串传递给视频元素的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>
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6644 次 |
| 最近记录: |