【问题标题】:Modify React Elements in ES6 using a for loop and setTimeout使用 for 循环和 setTimeout 在 ES6 中修改 React 元素
【发布时间】:2017-10-06 21:58:54
【问题描述】:

我正在尝试在我的 es6 组件中创建打字机动画like this(本质上,迭代地渲染其他传递的元素或字母)。然而,每当我执行/渲染这个组件时,所有渲染的都是较大集合“abc”中的第一个元素/字母“a”。超时时间工作正常,所以我认为 for 循环失败了。如何在 es6 中的 setTimeout 函数上正确运行 for 循环,以便呈现我的新元素?谢谢。

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

【问题讨论】:

    标签: javascript ecmascript-6 settimeout es6-modules


    【解决方案1】:

    由于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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-24
      相关资源
      最近更新 更多