const textInputRef = useRef();
useEffect(() => {
if (textInputRef && textInputRef.current) {
textInputRef.current?.focus(); // property 'focus' does not exist on type 'never'
}
}, []);
return (
<input ref={textInputRef} />
)
textInputRef.current?.focus()
线抛出property 'focus' does not exist on type 'never'
我在React 16.13.1, typescript 4.0.2使用钩子和函数组件
useRef
需要一个传递给它的类型。这是期望包含的值的类型。Typescript不能抓取你的代码来查看ref在哪里被使用,并从中找出类型。当没有默认值时,必须提供。
在你的例子中是:
const textInputRef = useRef<HTMLInputElement>(null);
看到操场