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);
相关推荐
ZhengEnCi32 分钟前
Hono 4 多库多模型服务的企业级 Monorepo 目录结构:npm workspaces 与 Turborepo 该怎么分层
typescript
浪遏1 天前
从命令到工作流:juejin-cli 如何让写作自动化更可靠
typescript
Highcharts.js1 天前
Highcharts Orbit 完全指南:把每一张图表变成交互式分析工具
react.js·前端框架·highcharts·orbit·使用指南·ai 图表·交互式分析工具
浪遏1 天前
07|网页上看着正常,导出的 PDF 为什么还会变样
typescript
浪遏1 天前
03|自动保存真正难的部分,是保存期间又发生了修改
typescript
浪遏1 天前
04|同一篇资料,怎样同时交给编辑器、搜索和 AI
typescript
浪遏1 天前
09|让 Mermaid 和 HTML 成为可编辑内容块
typescript
鸿蒙开发1 天前
小程序存档写到一半怎么办?双槽保存与损坏恢复实战
前端·javascript·react.js
️公子2 天前
可插拔 13 款实时棋牌对战平台实践:房间容器、Plugin SDK 与幂等账本
websocket·typescript·游戏开发·monorepo·插件架构·棋牌平台·实时对战
FungLeo2 天前
成为全栈·Vue 管理后台篇·Vue3 + Vite + Naive UI:后台工程基座怎么搭
前端·vue.js·ui·typescript·vite·前端工程化·biome