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);
相关推荐
晚安日记wanna21 小时前
SSR 为什么不适合登录态从水合冲突到缓存串号
前端·react.js·面试
晚安日记wanna21 小时前
TS const 类型参数一道面试题的四层追问
前端·面试·typescript
掰头战士21 小时前
你说你折这玩意干什么-agent工作的核心,还真得好好考虑怎么折叠上下文
typescript·llm·agent
ynchyong21 小时前
VUE 中 不能将类型“R[]”分配给类型“UnwrapRefSimple<R>[]”
typescript·vue·ts·unwraprefsimple
掰头战士1 天前
让散乱的工具调用成为正规军,今天咱们聊聊 Tool System管线的读写锁
typescript·llm·agent
半糖程序员1 天前
从零构建 Agent(5):让事件流同时提供过程和结果
typescript·agent
西瓜太郎12342 天前
外层模型卡片与分组详情成功率不一致,应该怎么排查?
前端·typescript·go·软件工程·react
掰头战士2 天前
MCP、Skill、Plugin,都是给agent拓展能力,到底有何区别?
typescript·llm·agent