通过遍历数组来改变元素的文本

React changing text of element by looping through array

我有一组文本项,如下所示

const sentences  = ['sentence one', 'sentence two', 'sentence three', 'sentence four']

我试图让元素文本循环遍历每个句子,每个句子显示五秒钟,向外打字效果,然后退格效果,然后输入下一个句子并循环。

我的代码将输入第一句话,退格,输入第二句话,然后它会退格并一遍又一遍地输入第二句话...知道我做错了什么吗?

这是我的代码

  const sentences = ['sentence one', 'sentence two', 'sentence three', 'sentence four']
  const [sentence, setSentence] = useState(sentences[0])
  let index = 0
  if(index < 3) {
    setInterval(() => {
      index++
      setSentence(sentences[index])
    }, 5000)
  }

每次安装组件时,index 变量都会再次设置为 0。 index 变量应存储在状态中:

const [index, setIndex] = useState(0)

您需要在 useEffect 内设置间隔,以防止无限重新安装。然后在你的 useEffect:

useEffect(() => {
  const interval = setInterval(() => {
      setIndex(index + 1)
    }, 5000)

  return (() => clearInterval(interval)) //This is a cleanup function
})

最后,您可以像 sentences[index] 一样渲染您的句子,而不需要 sentence 状态变量。你可以看看我为这个问题创建的codesandbox

这是你需要的东西,我刚刚编辑了上面的codesandbox https://codesandbox.io/s/heuristic-goodall-ypntd

import "./styles.css";
import { useState, useEffect } from "react";

const loopArr = [
  "sentence1",
  "sentence2",
  "sentence3",
  "sentence4",
  "sentence5",
  "sentence5 sentence5"
];

export default function App() {
  const [index, setIndex] = useState(0);

  useEffect(() => {
    const intervalDelayMilliseconds = loopArr[index].length * 500;
    const interval = setInterval(() => {
      setIndex((prevIndex) => {
        // reset index if current index is greater than array size
        return prevIndex + 1 < loopArr.length ? prevIndex + 1 : 0;
      });
    }, intervalDelayMilliseconds);

    return () => clearInterval(interval);
  });

  return (
    <div className="App">
      <div class="typewriter">
        <h1 key={loopArr[index]}>{loopArr[index]}</h1>
      </div>
    </div>
  );
}