javascript - 使用 node_modules 实现 Typed.js 时遇到问题
问题描述
我在使用 react 和 Node.JS 的网站中实现 typed.js 时遇到问题
我一直在尝试为 typed.js 导入节点模块。这是我不断回归的基本语法,但我似乎永远无法让它发挥作用。
"use strict"
import React from "react";
var $ = require("jquery")
var typed = require("typed.js")
$(function() {
typed.typed( {
strings: ["Text Data", "More Text Data"],
typeSpeed: 70,
backSpeed: 75,
loop: true,
});
});
export default function AboutMe( {typed}) {
return (
<div className="AboutMe">
<h1>I am <span id="typed"></span>
</h1>
</div>
);
}
我希望能够导入和操作数据。但不断收到诸如 TypeError: typed.typed is not a function 之类的错误
解决方案
有多个问题:
- 包中没有
typed
函数,它是一个你需要初始化的类,这就是你在控制台中出现这个错误的原因 - 您忘记将目标节点的 id 作为第一个参数传递
- 您正在尝试在向 DOM 写入任何内容之前执行该函数
我会在安装组件后使用反应生命周期来执行库。
使用 ES6,你可以让它像这样工作:
import React, { Component } from 'react';
import Typed from 'typed.js';
const animateText = () => (
new Typed('#typed', {
strings: ["Text Data", "More Text Data"],
typeSpeed: 70,
backSpeed: 75,
loop: true,
})
);
// Class component so you can use `componentDidMount` lifecycle
export default class AboutMe extends Component {
componentDidMount() {
// Will be executed after first `render`
animateText();
}
render() {
return (
<div className="AboutMe">
<h1>I am <span id="typed" /></h1>
</div>
);
}
}
在这里观看它的工作:https ://codesandbox.io/s/react-sandbox-cs84i?fontsize=14
推荐阅读
- c# - 如何将格式单元格从数据库保存到数据表c#
- delphi - 如何禁用 F1 并专注于菜单项?
- r - 运行调用结果
- javascript - 计算用户创建天数
- sql - 如何优化大表的 Postgresql ARRAY_AGG 查询?
- java - Java、MySQL DB、SpringBoot 和 Thymeleaf。如何使用 Thymleaf 从 2 个不同的类中提取一些字段以从数据库中获取数据
- android - 如何删除 ImageButton 周围的空白?
- typescript - 格式人(JsonBody
): T,可分配给类型“T”的约束,但可以用不同的子类型实例化 - mapping - “GPWRT_34065 [错误] Gpload 错误:意外错误——回溯写入日志文件”
- android - 获取元素 Jetpack Compose 的高度