我的项目是打字动画效果,在键入的单词的末尾我需要减慢闪光灯的速度。
我正在尝试使用setState功能设置间隔速度。唯一的问题是我不能在render方法中设置setState,但确切地说我可以访问我的计数器。而且我想我需要使用我的计数器状态才能知道何时需要减慢闪烁的速度。我希望我的描述有道理: - )
感谢您的帮助:)
这是我的代码:
import React, { Component } from 'react';
class TypeAnimation extends Component {
constructor(props) {
super(props);
this.state = {
sec: 0,
blinker: '',
blinkerSpeed: 100
};
}
componentDidMount() {
this.textInterval = setInterval(() => {
this.setState({
sec: this.state.sec + 1
});
}, 200);
this.blinkerInterval = setInterval(() => {
if (this.state.blinker === '') {
this.setState({
blinker: <span style={{ color: 'orange', lineHeight: '2rem' }}> | </span>
});
} else {
this.setState({
blinker: ''
});
}
}, this.state.blinkerSpeed); //here I would like to change the speed of the blinker with a state
}
render() {
const inText = this.props.text[0];
if (this.state.sec === this.props.text[0].length) {
clearInterval(this.textInterval);
}
const firstLine = inText.substr(0, this.state.sec);
return (
<div style={{ diplay: 'flex', justifyContent: 'center', marginTop: 30 }}>
<h1>
{firstLine}
{this.state.blinker}
</h1>
</div>
);
}
}
export default TypeAnimation;
答案 0 :(得分:1)
componentDidUpdate
。 clearInterval
不应该发生render
componentDidUpdate
,setState
。然后,您可以在该生命周期中使用componentDidUpdate(prevProps, prevState) {
const newSpeed = 500; // change this number
if (this.state.sec === this.props.text[0].length && this.state.blinkerSpeed !== newSpeed) {
clearInterval(this.textInterval);
this.setState({ blinkerSpeed: newSpeed })
}
}
。
import { Component, ElementRef, ViewChild } from '@angular/core';
import { trigger, state, style, animate, transition } from '@angular/animations';
@Component({
selector: 'my-app',
template: `
<div class="container">
<div class="scrolling-text" [@scroll]="state" (@scroll.done)="scrollDone()">Hover to pause!</div>
</div>
`,
styles: [`
.container {
height: 30px;
overflow: hidden;
position: relative;
width: 100%;
}
.scrolling-text {
position: absolute;
white-space: nowrap;
}
/* Below doesn't work to pause */
.scrolling-text:hover, .container:hover {
-moz-animation-play-state: paused;
-webkit-animation-play-state: paused;
animation-play-state: paused;
}
`],
animations: [
trigger('scroll', [
state('on', style({left: '-100px'})),
transition('* => *', [
style({left: '-100px'}),
animate(10000, style({left: '100%'}))
])
])
]
})
export class AppComponent {
state = 0;
scrollDone() {
this.state++;
}
}
在if语句中有另一个限定符,确保闪烁速度尚未更改,或者你将获得无限渲染循环,这一点至关重要。
编辑:
最后,我根本不会使用React来做到这一点。我会用CSS。通过使用react,您每隔__毫秒渲染一次状态,这对于性能来说非常糟糕