我在react.js 中重新启动计时器时遇到问题。我想要实现的是:当计时器达到某个值(如我的示例中的 f.ex 20)时,它会重新启动到 0 并自动继续,没有任何事件,自动再次计数。
提前谢谢您!
这是我的代码:
import React, { Component } from 'react';
require('../../sass/main.scss');
class TypeAnimation extends Component {
constructor(props) {
super(props);
this.state = {
sec: 0,
};
}
componentDidMount() {
this.textInterval = setInterval(() => {
this.setState({
sec: this.state.sec + 1
});
}, 100);
}
componentDidUpdate(prevProps, prevState) {
if (this.state.sec === 20) {
clearInterval(this.textInterval);
this.firstTimeout = setTimeout(() => {
this.setState({
sec: 0
});
}, 3000);
}
}
render() {
const inText = this.props.text[0];
const firstLine = inText.substr(0, this.state.sec);
return (
<div>
<h2>
{firstLine}
<span className='blinker'> | </span>
</h2>
</div>
);
}
}
export default TypeAnimation;
最佳答案
this.textInterval = setInterval(() => {
this.setState(prevState => ({
sec: prevState.sec < 20 ? prevState.sec + 1 : 0
}));
}, 1000);
关于javascript - 在 React.js 中自动重置计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48721596/