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);
相关推荐
低代码布道师3 小时前
第06篇:用户新增——React Hook Form + Zod 搭建可复用的表单体系
前端·react.js·前端框架
打工仔折腾 AI4 小时前
智能体开发实战:Agent架构拆解与ReAct执行循环工程落地
前端·后端·python·react.js·架构·langchain·ai agent 实战
htzyl2064 小时前
升级到 TypeScript 7:哪些 tsconfig 选项会直接报错
前端·typescript
king王一帅7 小时前
思考了很久,QuireKit 还是支持了 20 年前的 .doc,浏览器/Node 通用,MIT 开源
前端·typescript·开源
少年的范儿7 小时前
React Native + Expo 实战 14|管理远端列表:缓存、刷新与分页
react native·react.js·缓存
少年的范儿7 小时前
React Native + Expo 实战 13|实现登录:会话恢复、过期处理与账号隔离
javascript·react native·react.js
Amumu1213817 小时前
TypeScript学习: 基础知识(二)
开发语言·typescript·ecmascript
Amumu1213819 小时前
TypeScript学习: 进阶知识
开发语言·学习·typescript
码哥字节1 天前
Remotion Skills:用 React 代码做视频,简直太爽了
react.js
用户302822530681 天前
AI 视频图片运镜为什么会抖?帧率拉高也救不了多次取整
前端·人工智能·typescript