由微软推出的TypeScript自从一推出就广受关注,现在无论开发前端React/Vue,还是后端API,很多项目中都广泛接受了TypeScript。下面以如何定义主题为例,介绍如何通过TypeScript使用React中的useRef Hook。

TypeScript
一个简单的示例:
TypeScript
import { useRef } from "react";
export default function UseRefDemo() {
const inputRef = useRef<HTMLInputElement>(null);
const handleChange = () => {
console.log(inputRef.current?.value);
}
return (
<div>
<input type="text" ref={inputRef} onChange={ handleChange }/>
</div>
);
}需要注意的是,这里一定需要使用泛型来声明useRef中的数据类型:HTMLInputElement:
TypeScript
const inputRef = useRef<HTMLInputElement>(null);否则,再后面使用inputRef.current?.value的时候会报错:
TypeScript
console.log(inputRef.current?.value);其报错信息为:
TypeScript
Property 'value' does not exist on type 'never'.ts(2339)