类型 never 上不存在属性
初始化的时候没报错不一定没有问题!
·
场景
function testComponent {
const ref = useRef(null);
.....
ref.current.<method>(); // 此处报错
return <div ref={ref}>
}
报错:类型 never 上不存在属性<method>
思路
never 类型
- 当 typeScript 推断,某变量所有类型都不是的时候,将它的类型记为 never
- 函数永远不能返回值(不是返回 void )例如函数里面只有一个 exception,这个函数返回值的类型为 never
尝试改成
ref?.current?.<method>();
仍然报错
ref 在定义前使用
我在函数组件返回前使用了ref,这个时候ref还没定义。
使用useCallback(),把render的过程变成一个回调函数,把这个函数写在上面
function testComponent {
const ref = useRef(null);
.....
const renderTest = useCallback(()=>{
return <div ref={ref}>
})
ref.current.<method>(); // 此处报错
return <div>{renderTest()}</div>
}
仍然报错
最终解决
原来是 ref 初始化的时候没有加类型
改成
const ref: any = useRef(null);
就好了
(所以为什么不在初始化的时候报错啊!)
更多推荐
所有评论(0)