在反应组件中每1.5秒更改/随机更改文本

时间:2017-02-07 15:45:07

标签: javascript jquery reactjs react-router

我是新手做出反应,我想为我的应用程序的主屏幕做一些基本的事情。

我想用给定的数组在给定段落中每1.5秒更改一次最后一个文本。稍后我将添加一些动画但是现在我只想做基础知识。

在我的反应组件中,我有类似的东西:

import React, { Component } from 'react';
import './Home.css';

class Home extends Component {

  render() {
    let textArray = ['eat', 'sleep', 'drink', 'snore', 'foo', 'buzz', 'whatever'];
    let textThatChanges;

    for (var i = 0; i < textArray.length; i++) {
      textThatChanges = textArray[i];
    }

    return (
      <section>
        <h1>Hello, my name is Barry Allen</h1>
        <p>I like to <span> {textThatChanges}</span></p>
      </section>
    );
  }
}

export default Home;

在普通的jquery中,它看起来像下面的东西:

textShuffle = function(element, text, timer){
  var thisEl = document.getElementById(element),
    counter = 0,
    t = setInterval(function(){		
        if(counter == text.length -1){
            t = window.clearInterval(t);
        }
        setTimeout(function(){
            //change markup to next the next string
            thisEl.innerHTML = text[counter];
            counter++;						
        },310);
    }, timer);
  }
  
  
  
var shuffle1 = new textShuffle('foo', 
                               ['eat', 'sleep', 'drink', 'snore', 'foo', 'buzz', 'whatever'],
                               1500);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>
  I like to <span id='foo'>Play</span>
</h1>

2 个答案:

答案 0 :(得分:3)

import React, { Component } from 'react';
import './Home.css';

const textArray = ['eat', 'sleep', 'drink', 'snore', 'foo', 'buzz', 'whatever'];

class Home extends Component {
  constructor() {
    super();
    this.state = { textIdx: 0 };
  }

  componentDidMount() {
    this.timeout = setInterval(() => {
      let currentIdx = this.state.textIdx;
      this.setState({ textIdx: currentIdx + 1 });
    }, 1500);
  }

  componentDidUnmount() {
    clearInterval(this.timeout);
  }

  render() {
    let textThatChanges = textArray[this.state.textIdx % textArray.length];

    return (
      <section>
        <h1>Hello, my name is Barry Allen</h1>
        <p>I like to <span>{textThatChanges}</span></p>
      </section>
    )
  }
}

export default Home;

答案 1 :(得分:0)

awk -F, '{if(substr($2,1,3)=="301" && $15=="996" || $15=="429" && $5>=030000 && $5<=035000) print $2"|"$15"|"$5}' 2017020* | head -10

3014241320|996|235939
3017943809|996|235953