Javascript 如何在按钮标签上添加间隔?
我试图构建一个应用程序,相机每一分钟自动拍摄一次图像,我试图在按钮标签上添加间隔,这意味着当应用程序运行时,每一分钟自动拍摄一次图像Javascript 如何在按钮标签上添加间隔?,javascript,reactjs,setinterval,intervals,Javascript,Reactjs,Setinterval,Intervals,我试图构建一个应用程序,相机每一分钟自动拍摄一次图像,我试图在按钮标签上添加间隔,这意味着当应用程序运行时,每一分钟自动拍摄一次图像 import React, { Component } from 'react'; export class CameraFeed extends Component { processDevices(devices) { devices.forEach(device => { console.log(de
import React, { Component } from 'react';
export class CameraFeed extends Component {
processDevices(devices) {
devices.forEach(device => {
console.log(device.label);
this.setDevice(device);
});
}
async setDevice(device) {
const { deviceId } = device;
const stream = await navigator.mediaDevices.getUserMedia({ audio: false, video: { deviceId } });
this.videoPlayer.srcObject = stream;
this.videoPlayer.play();
}
async componentDidMount() {
const cameras = await navigator.mediaDevices.enumerateDevices();
this.processDevices(cameras);
}
takePhoto = () => {
const { sendFile } = this.props;
const context = this.canvas.getContext('2d');
context.drawImage(this.videoPlayer, 0, 0, 680, 360);
this.canvas.toBlob(sendFile);
};
render() {
return (
<div className="c-camera-feed">
<div className="c-camera-feed__viewer">
<video ref={ref => (this.videoPlayer = ref)} width="680" heigh="360" />
</div>
<button onClick={this.takePhoto}>Take photo!</button>
<div className="c-camera-feed__stage">
<canvas width="680" height="360" ref={ref => (this.canvas = ref)} />
</div>
</div>
);
}
}
import React,{Component}来自'React';
导出类CameraFeed扩展组件{
处理设备(设备){
devices.forEach(设备=>{
控制台日志(设备标签);
本装置(装置);
});
}
异步设置设备(设备){
const{deviceId}=设备;
const stream=await navigator.mediaDevices.getUserMedia({audio:false,video:{deviceId}});
this.videoPlayer.srcObject=流;
这个.videoPlayer.play();
}
异步组件didmount(){
const cameras=wait navigator.mediaDevices.enumerateDevices();
这是处理设备(摄像机);
}
拍照=()=>{
const{sendFile}=this.props;
const context=this.canvas.getContext('2d');
context.drawImage(this.videoPlayer,0,0680360);
this.canvas.toBlob(sendFile);
};
render(){
返回(
(this.videoPlayer=ref)}width=“680”heigh=“360”/
拍照!
(this.canvas=ref)}/>
);
}
}
首先,您需要跟踪间隔ID
this.intervalId = null;
然后,您创建一个事件处理程序,该事件处理程序将在单击按钮时触发,并将拍摄时间订阅到一个间隔
takePhotoEachDelay = (delay = 60 * 1000) => {
setInterval(this.takePhoto, delay);
}
卸载时,您需要从间隔中取消订阅,以避免任何不必要的行为
componentWillUnmount() {
if (this.intervalId) { clearInterval(this.intervalId); }
}
最后,
<button onClick={this.takePhotoEachDelay }>Take photo!</button>
拍照!
首先,您需要跟踪间隔ID
this.intervalId = null;
然后,您创建一个事件处理程序,该事件处理程序将在单击按钮时触发,并将拍摄时间订阅到一个间隔
takePhotoEachDelay = (delay = 60 * 1000) => {
setInterval(this.takePhoto, delay);
}
卸载时,您需要从间隔中取消订阅,以避免任何不必要的行为
componentWillUnmount() {
if (this.intervalId) { clearInterval(this.intervalId); }
}
最后,
<button onClick={this.takePhotoEachDelay }>Take photo!</button>
拍照!