惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Apple Machine Learning Research
Apple Machine Learning Research
aimingoo的专栏
aimingoo的专栏
H
Help Net Security
腾讯CDC
T
Tailwind CSS Blog
Hugging Face - Blog
Hugging Face - Blog
人人都是产品经理
人人都是产品经理
酷 壳 – CoolShell
酷 壳 – CoolShell
MongoDB | Blog
MongoDB | Blog
宝玉的分享
宝玉的分享
有赞技术团队
有赞技术团队
美团技术团队
雷峰网
雷峰网
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
博客园 - 司徒正美
博客园_首页
Recent Announcements
Recent Announcements
云风的 BLOG
云风的 BLOG
B
Blog RSS Feed
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
D
Docker
博客园 - Franky
Jina AI
Jina AI

时间的朋友

Windows 命令行密码重置 Anaconda安装 typescript 注解解读1 Konvajs Shape加载自定义图片 sshpass 使用 why-is-node-running webgl笔记 SharedArrayBuffer is not defined blender 常用快捷键 | 时间的朋友 vue -- v3.4commit提交记录2 vue2 升级vue3报错问题整理 着色器 expressjs 源码 hyper-V arch linux 网络配置 element input数字格式化 three 拼接货架 WebAudio笔记 Windows nginx重启bat脚本 vue -- v3.4commit提交记录 URI malformed vue3 -- Class 对象在组件中使用范例 | 时间的朋友 ruby 安装和升级 element-plus 老版本cascader使用卡死问题 vue3 内置Transition组件 | 时间的朋友 前端memo的实现 | 时间的朋友 Vue -- vue-class-component源码 | 时间的朋友 linux 优化脚本 typescript 装饰器 | 时间的朋友 microbundle 源码 | 时间的朋友 WSL2问题解决WslRegisterDistribution failed with error: 0x800701bc
React Usage Issue | 时间的朋友
2022-05-14 · via 时间的朋友

Published: · LastMod: January 04, 2023 · 311 words

not assignable to type LegacyRef<xxxxx> 🔗

useRef定义一个ref时,报不能推断类型

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import React, { useRef, RefObject } from 'react';

function Test() 
{
    const node = useRef<HTMLElement>(null);

    if (
        node &&
        node.current &&
        node.current.contains()
    ){ console.log("current accessed")}

    return <div ref={ node }></div>
}

因为useRef是使用HTMLElement定义的泛型,所以说不能推断,改成ref所对应的标签泛型就可以了

Cannot assign to ‘current’ because it is a read-only property 🔗

当在react中使用useRef定义ref时,报这样的错误, 因为结果走到React.RefObject

useRef有这3种定义

1
2
3
4
5
function useRef<T>(initialValue: T): MutableRefObject<T>;

function useRef<T>(initialValue: T|null): RefObject<T>;

function useRef<T = undefined>(): MutableRefObject<T | undefined>;
  1. useRef初始值设为null
  2. useRef定义了一个初始的类型
1
2
3
const elem = useRef<HTMLDivElement>(null);

type Test = typeof elem; // Test = React.RefObject<HTMLDivElement>
1
2
error expect@29.3.1: The engine "node" is incompatible with this module. Expected version "^14.15.0 || ^16.10.0 || >=18.0.0". Got "17.5.0"
error Found incompatible module.

如果是使用yarn安装时加上yarn --ignore-engines