此代码的上下文是打字机效果。我正在逐字母更新状态,该状态在span元素中呈现。当我将字母连接成一个字符串时,它首先起作用,但是几秒钟后浏览器停止更新该元素。它等待所有更新完成,然后最后一次再次更新文本。如果我将所有字母都添加到数组中,则浏览器会正确更新该元素。但是,当我检查元素时,我可以看到DOM正在正确更新。
为使问题更清晰,这里有一个gif of the browser animating the text
这是一个有效的版本,可复制该问题:https://codesandbox.io/s/jj8zym92q5
class Typewriter extends Component {
constructor() {
super()
this.state = {
display: ''
}
}
async type() {
const typeLetter = (letter) =>
new Promise(resolve => setTimeout(resolve, 70, letter))
.then(letter => this.setState({ display: this.state.display + letter }))
for (const letter of this.props.text) {
await typeLetter(letter)
}
}
componentDidMount() {
this.type()
}
render() {
return (
<span>{this.state.display}</span>
)
}
}
export default Typewriter;
CSS(使用Sass)
.typewriter {
font-size: 42px;
font-weight: 600;
&:after {
content: '_';
animation: blink_underline 1s step-end infinite;
font-weight: 300;
}
&.typing {
&:after {
animation: none;
}
}
}
@keyframes blink_underline {
from, to { opacity: 0 }
50% { opacity: 1; }
}