在TypeScript使用React forwardRef

React forwardRef 用于获取子结点的DOM元素引用。当结合TS使用时,需要注意类型断言。

import { forwardRef, useEffect } from "react";

const Test = forwardRef<HTMLDivElement>((props, ref) => {
  useEffect(() => {
      console.log(ref.current); 
  }, []);
  return <div ref={ref}>hello world!</div>;
});

console.log(ref.current) 会抛出

Property 'current' does not exist on type '((instance: HTMLDivElement | null) => void) | MutableRefObject'.

可以看出ref的类型签名为:

((instance: HTMLDivElement | null) => void) | MutableRefObject<HTMLDivElement | null>

即可能是函数,也可能是对象,也可能是null。

故需要排除null或者函数的情况,因为二者不可能有current属性。如下:

import { forwardRef, useEffect } from "react";

const Test = forwardRef<HTMLDivElement>((props, ref) => {
  useEffect(() => {
    if (typeof ref !== "function" && ref !== null) 
      console.log(ref.current);
  }, []);
  return <div ref={ref}>hello world!</div>;
});

你可能感兴趣的:(前端,typescript,react.js,javascript)