TS-React:useRef 使用

不能给 useRef 的 current 属性赋值,提示一下错误信息:

Cannot assign to 'current' because it is a read-only property.(不能给current属性复制,因为它是一个只读属性。)

代码如下所示:

typescript 复制代码
let cameraMediaStream = useRef<MediaStream>(null);

/**
 * 打开摄像头
 **/
const openCamera = async (cameraId = curCameraId) => {
    try {
      // 关闭已打开的摄像头
      if (cameraMediaStream) await closeCamera();
      // Cannot assign to 'current' because it is a read-only property.
      cameraMediaStream.current = await ImageCapture.openCamera({ cameraId, video: videoRef.current, width, height });
    }
    catch (err: any) {
    	// 错误信息提示...
    }
}

解决方案:将 current 属性变为非只读属性,useRef 的泛型参数中增加【| null】即可把 current 属性变为非只读属性。

typescript 复制代码
let cameraMediaStream = useRef<MediaStream | null>(null);
相关推荐
YFF菲菲兔20 小时前
React 事件系统:addTrappedEventListener
react.js
无情的西瓜皮21 小时前
MCP 协议实战:从零搭建一个 MCP 服务器(Node.js 版)
vue.js·人工智能·typescript·node.js
小妖66621 小时前
React input 输入卡顿问题
前端·javascript·react.js
退休倒计时1 天前
【每日一题】LeetCode 78. 子集 TypeScript
算法·leetcode·typescript
学习-学习1 天前
Node.js 现在能直接跑 TypeScript 了?Type Stripping 原理、限制与 tsx / ts-node 取舍
typescript·node.js
小二·1 天前
React 19 + Next.js 15 现代前端开发实战:App Router / Server Components / 流式渲染
前端·javascript·react.js
yume_sibai2 天前
大屏数据可视化 - 边框红绿呼吸灯实现详解
前端·信息可视化·typescript
YFF菲菲兔2 天前
React 事件系统:listenToAllSupportedEvents
react.js
光影少年2 天前
RN 渲染原理:不依赖WebView,原生控件渲染
前端·react native·react.js·前端框架
孟无岐2 天前
LayaAir IDE 插件开发入门:用 TypeScript 给编辑器加一个自己的面板
typescript·游戏开发·工程化·编辑器扩展·layaair·ide 插件