【发布时间】:2020-07-05 15:40:52
【问题描述】:
我正在迈出反应的第一步。我正在运行 Reactjs v16.11.0
我有触发网络摄像头的页面(在this mdn tutorial 之后)。所以我想在绘制所有元素时调用startup 函数。我试过window.addEventListener('load', startup, false);,但它没有调用任何函数。
所以我尝试了useEffectHook:
useEffect (() => {
startup();
}, []);
但它调用启动函数太快了,并且由于运行异步代码,DOM 中还没有一些元素 - video。
我的启动功能是这样的
const startup= () => {
video = document.getElementById('video');
let canvas: HTMLCanvasElement = document.getElementById('canvas') as HTMLCanvasElement;
const photo = document.getElementById('photo') as HTMLElement;
navigator.mediaDevices.getUserMedia({video: true, audio: false})
.then(function(stream) {
mediaStream = stream.getTracks()[0];
video.srcObject = stream;
video.play();
})
.catch(function(err) {
console.log("An error occurred: " + err);
});
if(video) {
video.addEventListener('canplay', function (ev: any) {
if (!streaming) {
height = video.videoHeight / (video.videoWidth / width);
// Firefox currently has a bug where the height can't be read from
// the video, so we will make assumptions if this happens.
if (isNaN(height)) {
height = width / (4 / 3);
}
video.setAttribute('width', width);
video.setAttribute('height', height);
canvas.setAttribute('width', width.toString());
canvas.setAttribute('height', height.toString());
streaming = true;
}
}, false);
//clearphoto(canvas, photo);
}
}
我正在使用功能组件(而不是类组件)。据我了解,componentDidMount 适用于类组件。我说的对吗?
如何做到只有每个元素都在DOM中才运行启动功能?
编辑:useEffect 钩子中的代码编辑,Jayraj 注意到了
【问题讨论】:
标签: reactjs react-hooks