报错类型“never”上不存在属性“childFocusFn”。ts(2339),如何进行避免呢?
我尝试使用 typescript创建一个 forwardRef + useImperativeHandle
的demo示例:demo如下:
import { forwardRef, useState, LegacyRef, useRef, Ref, createRef, useImperativeHandle } from 'react'
import './App.css'
//#region 子组件
const ChildComp = forwardRef((props, ref) => {
const childRef = createRef<HTMLInputElement>()
useImperativeHandle(ref, () => ({
childFocusFn: () => {
childRef.current?.focus()
console.log("childFocusFn called.")
}
}))
return <>
<input defaultValue="我是子组件" type='text' ref={childRef}></input>
</>
}
)
//#endregion
function App() {
const ref = useRef(null)
const clickFn = () => {
if(ref.current) {
ref.current.childFocusFn() // 这里报错:类型“never”上不存在属性“childFocusFn”。ts(2339)
}
}
return (
<>
<ChildComp ref={ref}></ChildComp>
<button onClick={clickFn}>点击调用子组件方法</button>
</>
)
}
export default App
但是见报错结果:
类型“never”上不存在属性“childFocusFn”。ts(2339)
请问这个应该如何做才能避免呢?
回复
1个回答

test
2024-08-11
const ref = useRef<{ childFocusFn: () => void }>(null);
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容