reactjs - 在 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 可以正确理解它。
解决方案
你需要做两件事。首先,就像您猜到的那样,您需要指定这是什么类型的 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 不要检查您的工作。如果你犯了一个错误并且它实际上可能是空的,打字稿不能告诉你,你可能会在运行时得到意想不到的行为。
推荐阅读
- r - 有什么方法可以在ggplot中使用计数统计来注释多个箱线图?
- docker - 有没有办法使用 conda 或通过 tar 文件安装 Boto3?
- angular - 在 Nginx Ingress AKS 上设置 Angular 应用程序
- if-statement - 基于另一个字段在 Tableau 中的排名
- mysql - 如何在SQL中检查一个孩子的所有父记录的列值
- javascript - 格式良好的 JSON 文件
- css - 改变整个页面的颜色
- python - 程序不允许选择的数字输出运行
- windows - UAC 提示期间的鼠标控制 (SendInput)
- c# - 如何在 WPF 运行时更改 Listview 中的图像?