gpt4 book ai didi

javascript - 在 react 组件中每 1.5 秒更改/改组文本

转载 作者:行者123 更新时间:2023-11-30 07:55:08 25 4
gpt4 key购买 nike

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

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

在我的 react 组件中,我有这样的东西:

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>

最佳答案

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;

关于javascript - 在 react 组件中每 1.5 秒更改/改组文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42094060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com