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);
相关推荐
Revolution616 小时前
React 组件重新渲染时,到底重新执行了什么
前端·react.js·面试
林焱_RPAAI7 小时前
影刀RPA技术深度:CSS选择器高级实战指南——伪类属性选择器与性能对比完全解析
vue.js·react.js
贩卖黄昏的熊10 小时前
NestJS简明教程——安全
开发语言·javascript·安全·typescript·nest.js
theoweb310 小时前
Typescript关于sort需要注意的地方
typescript
黄泉路醉s13 小时前
在Vant+Vue+TypeScript的H移动前端使用UnoCSS
前端·vue.js·typescript
名字还没想好☜14 小时前
React 受控输入框光标跳到末尾:格式化输入时的 selection 丢失 bug 与修复
前端·javascript·react.js·bug·react·next.js
10share14 小时前
React 新一代样式隔离方案 —— 编译时、零运行时、原生写法
前端·react.js
不好听61314 小时前
TypeScript 类型系统:`type` vs `interface` 与 `import type`
typescript
光影少年15 小时前
RN 的EventEmitter 双向通信
前端·react native·react.js
晓说前端1 天前
TypeScript 高级特性 —— 类型断言与泛型
前端·typescript