我正在尝试将组件修复为从网络摄像头流式传输数据。它可以成功渲染并成功访问网络摄像头。但是我不知道为什么视频标签不播放任何内容。如何解决这个问题?我想念什么?
export class WebcamStream extends React.Component {
constructor(props) {
super(props);
this.state = {
src: null
}
this.videoRef = React.createRef()
}
componentDidMount() {
// getting access to webcam
navigator.mediaDevices
.getUserMedia({video: true})
.then(stream => this.setState({src: stream}))
.catch(console.log);
}
render() {
return <video id={this.props.id}
ref={() => this.videoRef.srcObject = this.state.src}
width={this.props.width}
height={this.props.height}
autoPlay="autoplay"
title={this.props.title}></video>
}
}
答案 0 :(得分:2)
好吧,我发现了什么地方出了问题。根据{{3}},我需要使用current
属性来使节点可访问。因此,我的网络摄像头组件的完整工作示例:
export class WebcamStream extends React.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 id={this.props.id}
ref={this.videoTag}
width={this.props.width}
height={this.props.height}
autoPlay
title={this.props.title}></video>
}
}
this.setState
是在直接srcObject
更改诺言之前被删除的,但是我不确定是否采用这种React方式。也许更正确地将this.videoTag.current.srcObject = stream
代码作为setState回调进行了移植?
答案 1 :(得分:1)
此行未正确使用ref
:
ref={() => this.videoRef.srcObject = this.state.src}
就像在代码中一样,只需将src
设置为videoRef
即可,而ref={this.videoRef.srcObject}
不会被初始化,因此它永远不会到达视频标签。
您可以尝试:
.then(stream => {this.videoRef.srcObject = stream})
在componentDidMount中:
ref={(e) => e.srcObject = this.state.src}
或者简单地:
CellContentClick
答案 2 :(得分:0)
在使用相同的上述代码时,我也面临着相同的错误,它显示“ _this2.video未定义;无法访问其“当前”属性”,并且所有的事情都正确,获得了vedio许可,但未在其中显示vedio我的页面。
答案 3 :(得分:0)
对我有用的组件如下
import React, { useState, useEffect } from 'react';
export default function ModalVideo(props) {
const [video,]=useState(React.createRef());
const videoError=(error)=>{
console.log("error",error);
}
const handleVideo=(stream)=>{
video.current.srcObject = stream;
}
useEffect(() => {
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia;
if (navigator.getUserMedia) {
navigator.getUserMedia({video: true}, handleVideo, videoError);
}
});
return (
<div>
<video ref={video} autoPlay={true} />
</div>
)
}