使用for循环和setTimeout在ES6中修改React元素

3

我想创建一个打字机动画 (类似于这个) 在我的es6组件中,即迭代地渲染传递的额外元素或字母。然而,无论何时我执行/渲染此组件,所有被渲染的只是“abc”集合中的第一个元素/字母“a”。超时时间正常工作,所以我认为for循环失败了。在es6中如何正确运行一个for循环并使用setTimeout函数,以便我的新元素可以被渲染呢?谢谢。

import React from 'react';
import { CSSTransitionGroup } from 'react-transition-group';
import Radium from 'radium';

export default class Logo extends React.Component {
  constructor(props) {
    super();
    this.state = {
      final: ''
    }
    this.typeWriter = this.typeWriter.bind(this);
  }

  typeWriter(text, n) {
    if (n < (text.length)) {
      let k = text.substring(0, n+1);
      this.setState({ final: k });
      n++;
      setTimeout( () => { this.typeWriter(text, n) }, 1000 );
    }
  }

  render() {
    this.typeWriter('abc', 0);
    return (
      <div>
        <h1>{this.state.final}</h1>
      </div>
    );
  }
}

module.exports = Radium(Logo);
1个回答

3

由于this.typeWriter('abc', 0);位于render函数中,每当状态改变时,它都会运行typewriter方法,该方法将状态更新回a

this.typeWriter('abc', 0);移动到componentDidMount()。这将在组件完成渲染后启动打字机。

class Logo extends React.Component {
  constructor(props) {
    super();
    this.state = {
      final: ''
    }
    this.typeWriter = this.typeWriter.bind(this);
  }

  typeWriter(text, n) {
    if (n < (text.length)) {
      let k = text.substring(0, n+1);
      this.setState({ final: k });
      n++;
      setTimeout( () => { this.typeWriter(text, n) }, 1000 );
    }
  }
  
  componentDidMount() {
    this.typeWriter('abc', 0);
  }

  render() {
    return (
      <div>
        <h1>{this.state.final}</h1>
      </div>
    );
  }
}

ReactDOM.render(
  <Logo />,
  demo
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="demo"></div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接