Skip to content

Commit

Permalink
fix: 更新打字组件
Browse files Browse the repository at this point in the history
  • Loading branch information
weiqinke committed Feb 20, 2024
1 parent 994b920 commit baa8a8c
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 15 deletions.
27 changes: 21 additions & 6 deletions src/components/TypingCard/Typing.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,23 @@ class Typing {
public output;
public delay: number;
public chain;
public element;
public doneState: boolean;
public timer;

constructor(opts) {
this.opts = opts || {};
this.source = opts.source.current;
const element = document.createElement("div");
element.innerHTML = opts.data;
this.element = element;
this.output = opts.output;
this.delay = opts.delay || 120;
this.chain = {
parent: null,
dom: this.output,
val: []
};
if (!(typeof this.opts.done === "function")) this.opts.done = function () {};
this.doneState = false;
}

convert(dom, arr) {
Expand All @@ -36,9 +41,10 @@ class Typing {
}
return arr;
}

print(dom, val, callback) {
setTimeout(function () {
clearTimeout(this.timer);
this.timer = null;
this.timer = setTimeout(function () {
if (dom.current) {
dom.current.appendChild(document.createTextNode(val));
} else {
Expand All @@ -51,10 +57,11 @@ class Typing {
}, this.delay);
}
play(ele) {
if (this.doneState) return;
//当打印最后一个字符时,动画完毕,执行done
if (!ele.val.length) {
if (ele.parent) this.play(ele.parent);
else this.opts.done();
else this.done();
return;
}
const current = ele.val.shift(); //获取第一个元素,同时删除数组中的第一个元素
Expand All @@ -78,9 +85,17 @@ class Typing {
}
start() {
//初始化函数
this.chain.val = this.convert(this.source, this.chain.val);
this.chain.val = this.convert(this.element, this.chain.val);
clearTimeout(this.timer);
this.timer = null;
this.output.current.innerHTML = "";
this.play(this.chain);
}
done() {
this.doneState = true;
clearTimeout(this.timer);
this.timer = null;
}
}

export default Typing;
14 changes: 5 additions & 9 deletions src/components/TypingCard/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,26 +3,22 @@ import { Card } from "antd";
import Typing from "./Typing";

const TypingCard = (props: any) => {
const { title, source } = props;
const sourceEl: any = useRef();
const outputEl: any = useRef();

useEffect(() => {
const typing: any = new Typing({
source: sourceEl,
data: props.source,
output: outputEl,
delay: 30,
stopFlag: false
delay: 50
});
typing.start();
return () => {
typing.opts.done();
typing.done();
};
}, []);
}, [props]);

return (
<Card bordered={false} className="card-item" title={title}>
<div ref={sourceEl} style={{ display: "none" }} dangerouslySetInnerHTML={{ __html: source }} />
<Card bordered={false} className="card-item" title={props.title}>
<div ref={outputEl} style={{ fontSize: "1.5rem" }} />
</Card>
);
Expand Down

0 comments on commit baa8a8c

Please sign in to comment.