React+TypeScript教程之6 - useRef


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

TypeScript
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)

文章作者: 逻思
版权声明: 本博客所有文章除特別声明外,均采用 CC BY-NC-ND 4.0 许可协议。转载请注明来源 逻思 !
  目录