gpt4 book ai didi

javascript - 如何使用 React Hooks 获取网络摄像头?

转载 作者:行者123 更新时间:2023-11-30 14:04:44 25 4
gpt4 key购买 nike

我正在尝试使用 React Hooks 获取网络摄像头源以显示在我的应用程序上。我还需要能够从提要中捕获最新图像

我相信我有基础,但还缺少一些东西。

import React,{useState,useEffect} from "react"


export function VideoFeed(){
const[constraints] = useState({width:300,height:300})

useEffect(()=>{
navigator.mediaDevices.getUserMedia({video:true})
.then(stream=>{
let video = document.querySelector('video')
video.source = stream;
video.play();
})
.catch(e=>{
console.log(e)
})
})

return(
<video autoPlay ={true} id ="video"></video>
)
}

最佳答案

参见 How to access a DOM element in React?而不是 document.querySelector

useRef 一起应用时 Hook 并修复 useEffect 需要执行的频率,它看起来像这样:

export function VideoFeed() {
const videoEl = useRef(null)

useEffect(() => {
if (!videoEl) {
return
}
navigator.mediaDevices.getUserMedia({video:true})
.then(stream => {
let video = videoEl.current
video.srcObject = stream
video.play()
})
}, [videoEl])

return <video ref={videoEl} />
}

关于javascript - 如何使用 React Hooks 获取网络摄像头?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55655846/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com