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);
相关推荐
律宏阔7 小时前
微信小程序 + Taro 从 ESLint 迁移到 Oxlint 让项目代码检查速度提升近 12 倍
前端·typescript·eslint
瓦瓦gogo8 小时前
从一个 TypeScript 函数开始理解 MCP 协议
linux·ubuntu·typescript
ZhengEnCi12 小时前
React 19 加 Vite 6 企业级前端项目目录结构:无路由 SPA、zustand 与 Tailwind 4 的分层架构指南
react.js
用户2986985301412 小时前
React 前端实现 Excel 与 CSV 互转:基于 WebAssembly 的浏览器端方案
javascript·react.js·excel
ZhengEnCi1 天前
Hono 4 多库多模型服务的企业级 Monorepo 目录结构:npm workspaces 与 Turborepo 该怎么分层
typescript
浪遏2 天前
从命令到工作流:juejin-cli 如何让写作自动化更可靠
typescript
Highcharts.js2 天前
Highcharts Orbit 完全指南:把每一张图表变成交互式分析工具
react.js·前端框架·highcharts·orbit·使用指南·ai 图表·交互式分析工具
浪遏2 天前
07|网页上看着正常,导出的 PDF 为什么还会变样
typescript
浪遏2 天前
03|自动保存真正难的部分,是保存期间又发生了修改
typescript
浪遏2 天前
04|同一篇资料,怎样同时交给编辑器、搜索和 AI
typescript