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);
相关推荐
小李科技5 小时前
【性能优化】事件委托:目标定位与 React/Vue 实战
前端·vue.js·react.js·面试·性能优化·前端框架
csj505 小时前
前端基础之《React(16)—Modal组件封装》
前端·react.js
德尔塔A1 天前
中文全文检索加向量,我用 SQLite 做到零依赖
typescript
wflynn1 天前
GitHub 今日推荐|rea:用 MCP 把反编译器和 AI agent 接到一起的逆向工具
typescript·开源·github·agent·agent-skills·binary-analysis
德尔塔A1 天前
AI 改了 300KB 的文件,我让浏览器一屏都不多拿
typescript
德尔塔A1 天前
给 Agent 写终端界面,我一个 UI 库都没装
typescript
德尔塔A1 天前
同一条命令,在 Windows 上炸了三种方式
typescript
德尔塔A1 天前
同一个会话,终端和浏览器同时开着会发生什么
typescript
咚咚咚小柒1 天前
【前端】LangChain.js学习
前端·javascript·人工智能·typescript·langchain·vue·ai编程
螺丝钉tina1 天前
[Playwright][01] 从 Puppeteer 到 Playwright:为什么选择 Playwright + TypeScript?
前端·javascript·typescript