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);
相关推荐
YFF菲菲兔17 小时前
调度系统和调和系统的桥梁
react.js
YFF菲菲兔1 天前
commitRoot 源码解析
react.js
光影少年2 天前
react批量更新、同步/异步更新场景
前端·react.js·掘金·金石计划
YFF菲菲兔2 天前
completeRoot 源码解析
react.js
光影少年3 天前
React 合成事件机制、和原生事件区别、事件冒泡阻止
前端·react.js·掘金·金石计划
Momo__3 天前
TypeScript NoInfer<T>——精准控制泛型推断的工具类型
前端·typescript
YFF菲菲兔3 天前
finishConcurrentRender 源码解析
react.js
YFF菲菲兔3 天前
reconcileChildren 源码解析
react.js
还有多久拿退休金4 天前
Ant Design Tree 搜索定位避坑指南:虚拟滚动下如何实现高亮与精准定位
前端·react.js
光影少年4 天前
react 原理与进阶
前端·react.js·掘金·金石计划