1 回答
TA贡献1871条经验 获得超8个赞
有趣的问题!
我的建议是编写一个函数来知道该行中是否有未来的字符,另一个来显示未来的行(如果我们在最后一行,则返回第 0 行)。
另外,请注意. setState如果您当前构建的状态依赖于先例状态,则需要使用以下语法:
setState(previousState => { ... })
你可以试试我的解决方案:
import React from "react";
class AnimationTypingText extends React.Component {
state = {
text: "",
indexText: 0,
activeLetter: -1,
activeText: 0
};
idInterval = setInterval(() => this.addLetter(), 50);
addLetter = () => {
const txt = [
"HTML Lorem ipsum dolor sit amet consectetur",
"CSS adipisicing elit. Repellat, laudantium dolorum",
"JavaScript consequuntur dicta esse soluta aut assumenda",
"React error iusto qui atque necessitatibus ",
"Node tempore dolor laborum.",
"MongoDB Aspernatur quam voluptatum quis possimus."
];
const getNextLine = () => {
if (this.state.activeText >= txt.length - 1) {
return 0;
} else return this.state.activeText + 1;
};
const hasNextChar = () => {
if (this.state.activeLetter < txt[this.state.activeText].length - 1) {
return true;
} else return false;
};
if (hasNextChar()) {
this.setState(previousState => ({
text:
previousState.text +
txt[previousState.activeText][previousState.activeLetter + 1],
activeLetter: previousState.activeLetter + 1
}));
} else {
const nextLine = getNextLine();
this.setState({
activeText: nextLine,
text: "",
activeLetter: -1
});
}
};
render() {
return (
<div>
<div>
<p>{this.state.text}</p>
</div>
</div>
);
}
}
export default AnimationTypingText;
最后一件事,如果您不想像我的解决方案那样永远运行,请小心清除componentWillUnmount方法中的间隔。
添加回答
举报