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

React如何将摄像头类组件改写为函数组件并实现停止传输功能

报错原因

你遇到的报错是因为 React 的 useRef 返回的引用对象,其绑定的组件实例会统一挂载在 .current 属性下,你原有代码直接访问 webcamRef.video 属于路径错误,自然找不到对应的 srcObject 属性。

修正后的完整代码
import React from 'react';
import Webcam from 'react-webcam';

const Camera = () => {
  const webcamRef = React.useRef(null);
  const [imgSrc, setImgSrc] = React.useState(null);
  
  const stop = React.useCallback(() => {
    // 先加空值判断,避免ref未完成绑定时报错
    if (!webcamRef.current?.video?.srcObject) return;
    const stream = webcamRef.current.video.srcObject;
    const tracks = stream.getTracks();
    tracks.forEach(track => track.stop());
    webcamRef.current.video.srcObject = null;
  }, []); // webcamRef是稳定引用,不需要加入依赖数组
 
  const capture = React.useCallback(() => {
    if (!webcamRef.current) return;
    const imageSrc = webcamRef.current.getScreenshot();
    setImgSrc(imageSrc);
    stop();
  }, [stop, setImgSrc]); // 只需要加stop和setImgSrc即可

  return (
    <>
      <Webcam
        audio={false}
        ref={webcamRef}
        screenshotFormat="image/jpeg"
      />
      <button onClick={capture}>Capture photo</button>
      {imgSrc && (
        <img
          src={imgSrc}
          alt="captured"
        />
      )}
    </>
  ) 
}

export default Camera
核心修改说明
  • 所有对 webcam 实例的访问都需要通过 webcamRef.current 来获取,不能直接操作 webcamRef
  • 新增空值判断逻辑,避免组件初始化阶段、ref未绑定完成时调用方法触发空指针报错
  • 优化了 useCallback 的依赖项,useRef 返回的对象在组件全生命周期不会发生变化,不需要加入依赖数组

内容的提问来源于stack exchange,提问作者Nina

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 15:42:00