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);
相关推荐
yqcoder17 小时前
React 深度解析:类组件 (Class) vs 函数组件 (Function)
前端·javascript·react.js
zhensherlock20 小时前
Protocol Launcher 系列:Working Copy 文件操作与高级命令详解
javascript·git·typescript·node.js·自动化·github·js
lichenyang45321 小时前
从零到一:用 Taro + React 搭建数据采集小程序
react.js·小程序·taro
深海鱼在掘金1 天前
Next.js从入门到实战保姆级教程(第十一章):错误处理与加载状态
前端·typescript·next.js
深海鱼在掘金1 天前
Next.js从入门到实战保姆级教程(第十二章):认证鉴权与中间件
前端·typescript·next.js
暗不需求2 天前
React项目架构深度解析:从0到1理解现代前端工程化
前端·javascript·react.js
zhensherlock2 天前
Protocol Launcher 系列:Working Copy 提交与同步全攻略
javascript·git·typescript·node.js·自动化·github·js
changshuaihua0012 天前
useState 状态管理
开发语言·前端·javascript·react.js
Java后端的Ai之路2 天前
React 快速入门到精通教程:从零基础到能写项目
前端·react.js·前端框架
|晴 天|2 天前
Vue 3 + TypeScript + Element Plus 博客系统开发总结与思考
前端·vue.js·typescript