You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 16:03:10