如何在react中显示多个视频流



我试图通过将视频附加到数组并使用.map渲染视频来显示多个视频流。如果我使用下面的方法;未处理的拒绝(TypeError(:无法设置null的属性"srcObject";。如何在React中附加和显示多个视频流?

import React, {useState, useEffect} from 'react';
import {View} from 'react-native';

function createVideo(stream){
const localVideo = React.createRef();
localVideo.current.srcObject = stream;
return(
<View>
<video style = {{height: 100, width: 100}} ref = {localVideo} autoPlay />
</View>
)
}
const Test = () =>{
const videos = [];

navigator.mediaDevices.getUserMedia({video: true}).then(stream => {
videos.push(createVideo(stream));
})
return(
<View> 
{
videos.map(data => data)
}
</View>
)
}
export default Test;

组件函数体中的任何代码都将在每次渲染中运行(它是渲染循环的一部分(。

未测试:

const Video = ({ stream }) => {
const localVideo = React.createRef();
// localVideo.current is null on first render
// localVideo.current.srcObject = stream;
useEffect(() => {
// Let's update the srcObject only after the ref has been set
// and then every time the stream prop updates
if (localVideo.current) localVideo.current.srcObject = stream;
}, [stream, localVideo]);
return (
<View>
<video style={{ height: 100, width: 100 }} ref={localVideo} autoPlay />
</View>
);
};
const Test = () => {
// This would run on every render
// const videos = [];
const [streams, setStreams] = useState([]);
useEffect(() => {
// This shouldn't run on every render either
navigator.mediaDevices.getUserMedia({ video: true }).then(stream => {
setStreams([...streams, stream]);
});
}, []);
return (
<View>
{
streams.map(s => <Video stream={s} />)
}
</View>
)
}
export default Test;

相关内容

  • 没有找到相关文章

最新更新