React - 无法从网络摄像头流式传输视频

Ser*_*zzo 0 webcam html5-video reactjs

我正在尝试将我的组件修复为从网络摄像头流式传输数据。它呈现成功并成功访问网络摄像头。但我不知道为什么视频标签不播放任何内容。如何解决这个问题?我错过了什么?

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>
    }
}
Run Code Online (Sandbox Code Playgroud)

Ser*_*zzo 5

好吧,我已经找到了问题所在。根据文档,我需要使用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>
    }
}
Run Code Online (Sandbox Code Playgroud)

this.setStatesrcObject从 promise直接更改之前被删除,但我不确定这种 React 方式。也许,更正确的是将this.videoTag.current.srcObject = stream代码移动为 setState 回调?