【问题标题】:Use ityped init with useRef and useEffect in React with TypeScript在 React 和 TypeScript 中使用 typeped init 和 useRef 和 useEffect
【发布时间】:2021-09-10 01:56:21
【问题描述】:

尝试在 React 应用中实现 ityped。下面显示的代码应该在 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);需要以某种方式定义,以便来自typeped的init()可以正确理解。

【问题讨论】:

    标签: reactjs typescript tsx


    【解决方案1】:

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

    const textRef = useRef<HTMLSpanElement>(null);
    

    其次,即使使用该类型,就类型而言,textRef.current 仍然可以为 null。所以你要么需要在你的使用效果中添加代码来检查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 不要检查您的工作。如果你犯了一个错误并且它实际上可能是 null,typescript 不能告诉你,你可能会在运行时得到意外的行为。

    【讨论】:

      【解决方案2】:

      是的,您需要在 useRef 中添加类型,以便 Typescript 可以理解 ref 是针对 span 元素的。

      试试这个:const textRef = useRef&lt;HTMLSpanElement&gt;(null);

      【讨论】:

      • 它给了我同样的错误,但参数类型不同“'HTMLHeadingElement | null'类型的参数不可分配给'string | Element'类型的参数。”
      猜你喜欢
      • 2020-03-07
      • 2020-05-09
      • 2020-02-17
      • 2023-01-03
      • 2020-12-16
      • 2021-08-28
      • 2020-06-07
      • 2020-06-18
      • 2021-01-10
      相关资源
      最近更新 更多