我如何在这里使用 useEffect() / useState() 挂钩

How do i use useEffect() / useState() hooks here

我是React Js的新手,正在学习通过开发网站来实现某些功能。在这里我需要实现这样的东西 - https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_typewriter 但在页面加载时(不是在单击按钮时)

但是我们知道React有Hooks,在项目实现功能的时候需要用到。所以我尝试实现Hook,但在使用它时需要一些帮助,我在网上研究了一些例子但不理解并且不适合我目前的要求。

Main.js

import React, { useEffect } from 'react';
import '../App.css';

const Main = () => {

    useEffect( () => {
        var i = 0;
        var txt = 'Some Text here lorem ipsum lorem ipsum';
        var speed = 50; 
    
        function typeWriter()  {
            if (i < txt.length) {
                document.getElementById("typingText").innerHTML += txt.charAt(i);
                i++;
                setTimeout(typeWriter, speed);
            }
        }
    });

    return(
        <main>

            <div className='row'>                
                <img src='image.png' height='auto' width='100%' alt="banner"/>
                <div className='position-absolute top-50 start-0 translate-middle-y p-5'>
                    <div class="card bg-black" style={{width: '30%'}}>
                        <div class="card-body text-white fw-bold">
                            <h1 id="typingText"></h1>
                        </div>
                    </div>
                </div>
            </div>
      </main>
    );

export default Main;

首先,您缺少挂钩的依赖项数组。这个prop非常重要,否则useEffect hook会一直调用,导致调用溢出

如果我明白你想要什么,输入的文本应该每 x 毫秒改变一次。 useEffect 会完成这项工作。在这种情况下,当组件挂载时,您希望仅运行,挂钩的依赖数组将为空([])。在挂钩内部,您可以设置一个间隔,以保持 运行ning 您想要的功能。通过这个简短的解释,您可以:

import React, { useEffect, useState } from 'react';
import '../App.css';

const Main = () => {
    // We will keep track of how many letters are being displayed
    const [index, setIndex] = useState(0);

    const type = () => {
        setIndex((prev) => Math.min(prev + 1, 50));
    };

    useEffect(() => {
        const id = setInterval(type, 500);

        // It is important to clear the interval when the component unmounts!
        return () => clearInterval(id);
    }, []); // We are setting an empty dep array

    return (
        <main>
            <div className='row'>
                <img src='image.png' height='auto' width='100%' alt='banner' />
                <div className='position-absolute top-50 start-0 translate-middle-y p-5'>
                    <div class='card bg-black' style={{ width: '30%' }}>
                        <div class='card-body text-white fw-bold'>
                            <h1 id='typingText'>
                                {'Your text'.substring(0, index)}
                            </h1>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    );
};

export default Main;

综上所述,我们在做的是:

  1. 正在设置 500 毫秒后重复的间隔。如代码中所述,一旦组件卸载,清除间隔至关重要。 setInterval returns 区间的标识,用于标识用clearInterval移除的区间。
  2. 我们不使用 window 来操纵 DOM,而是跟踪状态,增加要从我们的字符串中显示的字母。
  3. 最后,我们将显示的字符串从 0“剪切”到当前索引,每 500 毫秒递增一次,创建打字机效果。

希望已经清楚了!

I recommend you take a look at the react hooks documentation.