使用 node_modules 实现 Typed.js 时遇到问题
Trouble implementing Typed.js using node_modules
我在使用 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
函数,是class需要初始化的,所以控制台报这个错误
- 您忘记将目标节点的 ID 作为第一个参数传递
- 您试图在向 DOM
写入任何内容之前执行函数
我会在挂载组件后使用 React 生命周期来执行库。
使用 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
我在使用 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
函数,是class需要初始化的,所以控制台报这个错误 - 您忘记将目标节点的 ID 作为第一个参数传递
- 您试图在向 DOM 写入任何内容之前执行函数
我会在挂载组件后使用 React 生命周期来执行库。
使用 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