【问题标题】:How to change css class after 60 seconds in react JS如何在 React JS 中 60 秒后更改 css 类
【发布时间】:2021-08-07 16:19:58
【问题描述】:

我在 react JS 中有一个动态生成的表格,格式如下:

<table>
<tr className="Green"> // This class will be assigned at sometime say 10 AM
<td>Row 1</td>
<td>Row 2</td>
</tr>

<tr className="Green"> // this class will be assigned at another time say 10:01 AM
<td>Row 1</td>
<td>Row 2</td>
</tr>

<tr className="Green"> // this class will be assigned at other time say 10:02 AM
<td>Row 1</td>
<td>Row 2</td>
</tr>
</table>

现在我的问题是我想在分配后 60 秒后删除“绿色”类。表示第一堂课将在上午 10:01 移除,而其他课程将分别在上午 10:02 和 10:03 移除。

“绿色”类是不可预测的。它将被随机分配给

同时可以有多个“绿色”类

我怎样才能做到这一点?不会有固定的编号,因为它们都是动态生成的。请原谅我的英语不好。

【问题讨论】:

  • 我已经在 React 中使用正确的方式提交了一个有效的答案,请看一下,谢谢

标签: javascript reactjs next.js


【解决方案1】:

这是在 React 中更新 className 的正确方法。

首先,您可以将所有className 值存储在一个数组中(例如['green', 'green']),然后将变量放入一个状态变量中(例如isColored。

然后,在 useEffect 挂钩中使用 setTimeout 更新每个 className。在for 循环中为一个className 创建一个setTimeout。

为简化返回组件,您可以使用map 函数对状态变量(isColored)。

这里是演示https://codesandbox.io/s/jovial-curie-sm34k?file=/src/App.js。

这是代码。

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

export default function App() {
  const [ isColored, setIsColored ] = useState(['green', 'green'])

  useEffect(() => {
    let timer = []
    for(let i = 0; i < isColored.length; i++) {
      setTimeout(() => {
        timer[i] = setIsColored(previousValue => {
          let newValue = [...previousValue]
          // update the value of className here for example 'blue'
          // use '' to remove the className
          newValue[i] = ''
          return newValue
        })
      }, 60000 * (i + 1))
    }
    return () => {
      clearTimeout(timer)
    }
  }, [])

  return (
    <div>
      {isColored.map((item, index) => (
        <div 
          key={index}
          className={item}
        >
        </div>
      ))}
    </div>
  );
}

【讨论】:

    【解决方案2】:

    不确定这是否可行。

    const remove = () => {
      setTimeout(() => {
        const elements = document.getElementsByClassName('green')
    
        if (elements.length > 0) {
          elements[elements.length - 1].classList.remove('green')
    
          if (elements.length !== 1) {
            remove()
          }
        }
      }, 60000)
    }
    

    或者类似的东西,你可以根据你想要做什么来稍微改变一下。

    【讨论】:

      【解决方案3】:

      根据 cmets 更新。

      您正在动态应用您的 green 类并希望突出显示您的表格行一分钟。您可以直接通过 CSS 执行此操作:

      .green {
        animation: highlight 60s;
      }
      
      @keyframes highlight {
        from,
        99% {
          color: green;
        }
        to {
          color: initial;
        }
      }
      

      然后,如果你想真正删除这个类,你可以在你的桌子上监听animationend 事件。然后删除 green 类:

        useEffect(() => {
          const classRemover = (event) => {
            event.target.classList.remove('green');
          };
      
          const tableToWatch = document.querySelector('#watch-this-table');
          tableToWatch.addEventListener('animationend', classRemover);
      
          return () => {
            tableToWatch.removeEventListener('animationend', classRemover);
          };
        }, []);
      

      忽略下面的内容。

      如果您的结构与您在问题中发布的结构相同,那么您可以直接使用Node.nextSibling 以及setInterval() 方法,如下所示:

      import { useEffect } from 'react';
      
      const IndexPage = () => {
        useEffect(() => {
          const interval = setInterval(() => {
            try {
              const current = document.querySelector('.green.active');
              current.classList.remove('active');
              current.nextSibling.classList.add('active');
            } catch {
              clearInterval(interval);
            }
          }, 60 * 1000);
          return () => {
            clearInterval(interval);
          };
        }, []);
      
        return (
          <>
            <table>
              <tbody>
                <tr className="green active">
                  <td>Row 1</td>
                  <td>Row 2</td>
                </tr>
      
                <tr className="green">
                  <td>Row 1</td>
                  <td>Row 2</td>
                </tr>
      
                <tr className="green">
                  <td>Row 1</td>
                  <td>Row 2</td>
                </tr>
              </tbody>
            </table>
            <style jsx global>{`
              .green.active {
                color: green;
              }
            `}</style>
          </>
        );
      };
      
      export default IndexPage;
      

      【讨论】:

      • 感谢您的回答。但是“绿色”类是不可预测的。它将被随机分配给
      • @HarenSarma 随机分配是什么意思?你能解释一下用例是什么吗?您究竟是如何向&lt;tr&gt; 申请课程的?
      • 我正在使用数学,如果一个数据的值大于前一个,则 将是绿色背景 60 秒。可以同时有2-3个数据高于之前的数据。然后所有这些 将变绿 60 秒。
      • 基本上你想改变删除绿色类的应用程序 60 年代后,而不考虑其他表行?有点突出它一分钟?
      • @HarenSarma 我已经更新了我的答案,给它看一次。
      【解决方案4】:

      这是一个想法。创建两个类似的函数:

      let displayGreen = true
      
      function resolveAfter60Seconds() {
        return new Promise(resolve => {
          setTimeout(() => {
            resolve('resolved');
          }, 60000);
        });
      }
      
      async function asyncCall() {
        console.log('calling');
        const result = await resolveAfter60Seconds();
        displayGreen = false
        console.log(result);
        // expected output: "resolved"
      }
      
      asyncCall();
      

      我相信这将等待 60 秒才能运行,并且在此之后,诸如 displayGreen 之类的变量将等于 false。只有当该变量为真(条件渲染)时,您才能渲染绿色 div。 希望这行得通!

      【讨论】:

      • 如果你能告诉它是如何工作的就太好了
      猜你喜欢
      相关资源
      最近更新 更多
      热门标签