本文介绍了在React组件中每1.5秒更改/改组文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是新来的反应者,我想为我的应用程序的主屏幕做一些基本的事情.
I am new to react and I wanted to do something a bit basic for my home screen of my application.
我想使用给定数组在给定段落中每1.5秒更改最后一个文本.稍后我将添加一些动画,但是现在我只想做基础.
I would like to change the last text every 1.5 seconds in a given paragraph with the given array. Later on I will add some animation but for right now I just wanted to do the basics.
在我的react组件中,我有类似以下内容:
In my react component, I have something like this:
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中,它看起来像下面的东西:
In plain jquery it would look like something below:
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>
推荐答案
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;
这篇关于在React组件中每1.5秒更改/改组文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!