【问题标题】:How to resolve these TypeScript errors when using React refs?使用 React refs 时如何解决这些 TypeScript 错误?
【发布时间】:2020-06-25 00:27:28
【问题描述】:

我正在设置一个 ref 并像这样输入它:

  const audioElem = useRef<HTMLAudioElement>();

然后当我这样使用它时:

  <audio ref={audioElem}></audio>

它会导致这个错误:

(JSX 属性) ClassAttributes.ref?: string | (((实例:HTMLAudioElement | null)=> void)| React.RefObject

并像这样使用:

audioElem.current.style.border = '2px solid red';

导致此错误:

(属性) MutableRefObject.当前: HTMLAudioElement | undefined Object 可能是“未定义”。

我怎样才能摆脱这些错误?

【问题讨论】:

  • 考虑添加if statement 以检查current 是否有值或将其放入useEffect
  • 您使用的是什么版本的打字稿?如果在分配给元素之前创建并使用了 ref,则可以未定义 current 属性。虽然if 检查可以确保current 未被定义,但更优雅的方法是使用optional-chaining 3.7 及更高版本。这看起来像audioElem.current?.style.border = '2px solid red';

标签: reactjs typescript


【解决方案1】:

在 React 中,引用可能是 null。 Typescript 抱怨你没有考虑到这种可能性。

要解决第一个问题,请将null 传递给useRef,如下所示:

const audioElem = useRef<HTMLAudioElement>(null);

要解决第二个问题,请添加一个检查 audioElem.currentif 语句,如下所示:

if(audioElem.current) {
    audioElem.current.style.border = '2px solid red';
}

【讨论】:

  • 只是为了添加更多信息:此博客对此问题进行了完整解释,并提供了有关如何将 Typescript 与 React Hooks 一起使用的更多“提示”:fettblog.eu/typescript-react/hooks/#useref
猜你喜欢
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 2013-09-01
  • 1970-01-01
  • 2013-07-22
  • 2021-07-24
  • 2014-02-19
  • 1970-01-01
相关资源
最近更新 更多