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);
相关推荐
放下华子我只抽RuiKe512 小时前
FastAPI 全栈后端(三):数据库与 ORM
前端·数据库·react.js·oracle·性能优化·前端框架·fastapi
meilindehuzi_a13 小时前
构建基于 RESTful 架构的 TodoList 全栈应用:从前后端理论到 TypeScript/Bun 实战
架构·typescript·restful
云水一下15 小时前
Vue.js从零到精通系列(七):高级特性实战——Teleport、异步组件、自定义指令与TypeScript深度结合
前端·vue.js·typescript
濮水大叔15 小时前
浅论CabloyJS全栈框架提供的“两级页签”机制
typescript·node.js·next.js
Asize15 小时前
Bun + TypeScript:AI 时代的后端开发入门
人工智能·typescript·bun
oioihoii17 小时前
探索React与Microi吾码的完美结合:快速搭建项目,低代码便捷开发教程
react.js·低代码·rxjava
超哥--1 天前
B站视频内容智能分析系统(九):React 前端与管理面板
前端·react.js·前端框架
退休倒计时1 天前
【每日一题】LeetCode 53. 最大子数组和 TypeScript
数据结构·算法·leetcode·typescript
光影少年1 天前
懒加载与分包:React.lazy + Suspense
前端·react.js·掘金·金石计划