首页 > 解决方案 > 在 React 和 TypeScript 中使用 typeped init 和 useRef 和 useEffect

问题描述

尝试在 React 应用程序中实现typeped 。下面显示的代码应该在 JSX 中工作;然而,这个 React 应用程序是用 Typescript (TSX) 编写的,这就是它失败并出现类型错误的原因。

“Intro.tsx”组件:

import React, { useEffect, useRef } from 'react';
import { init } from 'ityped';
import "./intro.scss";

export default function Intro() {

    const textRef = useRef(null);

    useEffect(() => {
        init(textRef.current, { 
            showCursor: false, 
            strings: ['Web developer', 'Logo designer'] 
        })
    }, []);
    return (
        <div className="intro" id="intro">
            <div className="left">
                <div className="imgContainer">
                    <img src="assets/man.png" alt="" />
                </div>
            </div>
            <div className="right">
                <div className="wrapper">
                    <h2>Hi there, I'm</h2>
                    <h1>Andreas Petersen</h1>
                    <h3>A <span ref={textRef}></span> </h3>
                </div>
                <a href="#portfolio">
                    <img src="assets/down.png" alt="" />
                </a>
            </div>
        </div>
    )
}

错误如下: 错误信息

我的猜测是const textRef = useRef(null);需要以某种方式定义,以便init()从 typeped 可以正确理解它。

标签: reactjstypescripttsx

解决方案


你需要做两件事。首先,就像您猜到的那样,您需要指定这是什么类型的 ref:

const textRef = useRef<HTMLSpanElement>(null);

其次,即使使用该类型,textRef.current就类型而言,仍然可以为空。所以你要么需要在你的使用效果中添加代码来检查null:

useEffect(() => {
  if (!textRef.current) {
    return;
  }
  init(textRef.current, { 
    showCursor: false, 
    strings: ['Web developer', 'Logo designer'] 
  })
}, []);

或者,如果您确信在第一次渲染后它不可能为 null(即,您无条件地将它传递给将使用它的组件),您可以使用非 null 断言 ( !)坚持打字你知道它不为空:

useEffect(() => {
  init(textRef.current!, { 
    showCursor: false, 
    strings: ['Web developer', 'Logo designer'] 
  })
}, []);

请注意,第二个选项意味着您告诉 typescript 不要检查您的工作。如果你犯了一个错误并且它实际上可能是空的,打字稿不能告诉你,你可能会在运行时得到意想不到的行为。


推荐阅读