简体   繁体   English

使用node_modules实现Typed.js遇到麻烦

[英]Trouble implementing Typed.js using node_modules

I am having trouble implementing typed.js into my website that uses react and Node.JS 我在使用react和Node.JS的网站中实现typed.js时遇到问题

I keep attempting to import the node module for typed.js. 我一直尝试为typed.js导入节点模块。 This is the basic syntax I kept coming back to, but I could never seem to make it work. 这是我不断回到的基本语法,但是我似乎永远无法使它起作用。

"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>
  );
}

I want to be able to import and manipulate the data. 我希望能够导入和处理数据。 But continually keep getting the errors such as TypeError: typed.typed is not a function 但是不断出现诸如TypeError之类的错误:typed.typed不是函数

There's multiple issues: 存在多个问题:

  • There's no typed function in the package, it's a class you need to initialize, that's why you have this error in console 程序包中没有typed函数,这是您需要初始化的类,这就是为什么在控制台中出现此错误的原因
  • You forgot to pass the id of your targeted node as first argument 您忘记将目标节点的ID作为第一个参数传递
  • You're trying to execute the function before writing anything to the DOM 您正在尝试执行功能,然后再将任何内容写入DOM

I would use the react lifecycle to execute the lib after mounting the component. 安装组件后,我将使用react生命周期执行lib。

Using ES6 you can make it work like this: 使用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>
    );
  }
}

Watch it work here: https://codesandbox.io/s/react-sandbox-cs84i?fontsize=14 在这里观看它的工作: https : //codesandbox.io/s/react-sandbox-cs84i?fontsize=14

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM