简体   繁体   English

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

[英]Modify React Elements in ES6 using a for loop and setTimeout

I am trying to create a typewriter animation like this in my es6 component (essentially, iteratively renders additional passed elements or letters). 我想创建一个打字机动画像这样在我的ES6组件(本质上,反复地提供了额外的传递的元素或字母)。 However, any time I execute / render this component, all that is rendered is the first element / letter, 'a', of the larger set, 'abc'. 但是,每次执行/渲染此组件时,渲染的所有内容都是较大集合的第一个元素/字母“a”,“abc”。 The timeout period is working fine, so I think that the for loop is failing. 超时时间正常,所以我认为for循环失败了。 How do I properly run a for loop over a setTimeout function in es6 such that my new elements will render? 如何在es6中的setTimeout函数上正确运行for循环,以便我的新元素将呈现? Thanks. 谢谢。

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);

Since this.typeWriter('abc', 0); 由于this.typeWriter('abc', 0); is in the render function, whenever the state changes, it runs the typewriter method, which updates the state back to a . render函数中,只要状态发生变化,它就会运行typewriter方法,将状态更新回a

Move the this.typeWriter('abc', 0); 移动this.typeWriter('abc', 0); to componentDidMount() . componentDidMount() It will start the type writer when the component has finished rendering. 它将在组件完成渲染时启动类型编写器。

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM