TS-React:useRef 使用

不能给 useRef 的 current 属性赋值,提示一下错误信息:
Cannot assign to ‘current’ because it is a read-only property.(不能给current属性复制,因为它是一个只读属性。)

代码如下所示:

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 属性变为非只读属性。

let cameraMediaStream = useRef<MediaStream | null>(null);

你可能感兴趣的:(TypeScript,react.js,typescript)