React类组件转函数组件:代码写法是否正确?
React类组件转函数组件的正确性判断
你的修改方向是对的,但还有两处关键细节需要补充:
已正确的部分
在函数组件中,通过useRef创建的ref变量无需通过this访问,所以修改后的remoteVideoref.current.srcObject = e.streams[0]是正确的,完美替代了类组件里的this.remoteVideoref.current写法。
需要修正的遗漏点
原类组件中的this.pc在函数组件里也不能保留this.——因为函数组件没有实例对象this,你需要根据pc的实际定义方式调整:
- 如果
pc是通过useRef保存的连接实例(比如const pcRef = useRef(new RTCPeerConnection())),要写成pcRef.current.ontrack - 如果
pc是直接声明的变量,直接写pc.ontrack即可
完整的函数组件示例代码
import { useRef, useEffect } from 'react'; function VideoCallComponent() { const remoteVideoref = useRef(null); const pcRef = useRef(new RTCPeerConnection()); useEffect(() => { const pc = pcRef.current; pc.ontrack = (e) => { remoteVideoref.current.srcObject = e.streams[0]; }; // 组件卸载时清理资源 return () => { pc.ontrack = null; pc.close(); }; }, []); return <video ref={remoteVideoref} autoPlay playsInline />; }
内容的提问来源于stack exchange,提问作者mickey
相关产品推荐
相关产品推荐

