首页 > 解决方案 > 使用 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 之类的错误

标签: javascriptjqueryreactjstyped.js

解决方案


有多个问题:

  • 包中没有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


推荐阅读