我有一个基本的反应组件,我正在尝试访问 navigator.mediaDevices.getUserMedia 中的视频。但是,我不断收到“无法将属性“srcObject”设置为 null”
import React, {Component} from 'react';
export default class Example extends Component{
render(){
const video = document.querySelector('video');
const constraints = {video:true}
navigator.mediaDevices.getUserMedia(constraints).then(
(stream) => {video.srcObject = stream})
return(
<div>
<video>
</video>
</div>
)
}
}
Run Code Online (Sandbox Code Playgroud)
以上返回:
无法将属性“srcObject”设置为 null
有任何想法吗?
这是从网络摄像头流式传输视频的 React 方式。
使用钩子:
import { useRef, useEffect } from 'react';
export default function App() {
const videoRef = useRef(null);
useEffect(() => {
const getUserMedia = async () => {
try {
const stream = await navigator.mediaDevices.getUserMedia({video: true});
videoRef.current.srcObject = stream;
} catch (err) {
console.log(err);
}
};
getUserMedia();
}, []);
return (
<div>
<video
ref={videoRef}
autoPlay
/>
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
使用类组件:
class Example extends Component {
constructor(props) {
super(props);
this.videoTag = React.createRef()
}
componentDidMount() {
// getting access to webcam
navigator.mediaDevices
.getUserMedia({video: true})
.then(stream => this.videoTag.current.srcObject = stream)
.catch(console.log);
}
render() {
return (
<video
ref={this.videoTag}
autoPlay
/>
)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17456 次 |
| 最近记录: |