javascript - 如何将 React Hooks 与 video.js 一起使用?
问题描述
我在 React 中使用 video.js。我尝试迁移到 React Hooks。
我的反应版本是 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 HooksuseRef
而不是refs
。任何指南都会有所帮助。
解决方案
您正在将一个字符串传递给视频元素的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>
);
}
推荐阅读
- javascript - Chartkick-vue 条形图-“horizontalBar”不是注册控制器
- linux - 将 netcore 3 应用程序发布到树莓派 3(32 位/x86)
- gatsby - 禁用客户端路由
- c# - 如何使用 C# 以编程方式将 RTF 文本插入 PowerPoint 文本框架?
- c# - 使用 Lamar DI 容器,如何使用给定类型的 lambda 构建对象?
- python - 如何获取 S3 存储桶中所有不同前缀的列表?
- excel - 如何动态更新excel中的数据透视表?
- java - 如何使用带有 /actuator/prometheus 的 Micrometer 格式将 Apache Camel 指标(如 metrics:timer:simple.timer)输出到 Prometheus
- python - ValueError:预期张量是大小为(C,H,W)的张量图像。得到 tensor.size() = torch.Size([1800, 800])
- c# - 从与其他id列表匹配的sql表中获取id列表的有效方法