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);
相关推荐
aloha_7891 小时前
HTML、JavaScript 与 TypeScript 基础速查
javascript·typescript·html
空中湖13 小时前
用 React 写数据大屏:为什么我不建议用图表库
前端·react.js·前端框架
离歌漠17 小时前
《我用 Tauri 做了一个本地开发工具箱》
rust·typescript·vue
enjoy编程1 天前
playwright学习-I
typescript·vue·nodejs·1024程序员节·playwright
iDao技术魔方1 天前
Bun v1.4.4 实战:用 bun fmt 替掉 prettier 的 5 个步骤
typescript·1024程序员节
梅雅达编程笔记1 天前
Day 17 | uni-app 小程序:前端从零搭建
微信小程序·typescript·uni-app·vue3·pinia·前端开发·全栈
康小旺2 天前
TypeScript 编译器开始卷 Rust 了:Cloudflare 的 tsrs 到底想干嘛?
rust·typescript
来一首_We_go2 天前
React Flow Pro 高级交互实现
前端·react.js
weedsfly2 天前
React 不可变数据:为什么页面“明明数据变了却不更新
前端·javascript·react.js
nyaomaru2 天前
is-kit 达成 100 Stars ⭐🎉 从 50 到 100,发生了什么?
前端·typescript