【问题标题】:How to get the old value of variable stored in a new variable when the variable changes in React?React中变量更改时如何获取存储在新变量中的变量的旧值?
【发布时间】:2021-02-07 15:44:09
【问题描述】:

我在下面有这段代码,它将一个类添加到它需要添加的相应元素中。

const hash = window.location.hash;

if (hash) {
  const id = symbolRemover(hash) + "__list";
  document.getElementById(id).classList.add("active");
}


问题是每次hash 更改时都会添加类。但是随着hash 的更改,之前添加的active 类仍然存在,并且每次hash 更改它都会添加,但我想随着hash 的更改而从中删除active 的类。所以只有一个类为active的唯一元素。

我在想,每当哈希发生变化时,我们都会以某种方式将id 保存在另一个变量中。有点像:

const oldId = id;
// I know this does not work.

我是 React 新手,所以不太了解。任何帮助将不胜感激。

谢谢。

【问题讨论】:

  • 该代码看起来不像 React 代码。通常在 React 中你不会使用 classList,你只需将要渲染的内容更改为 className 属性。
  • 请用minimal reproducible example 更新您的问题,以证明问题,最好是使用堆栈片段([<>] 工具栏按钮)可运行的问题。 Stack Snippets 支持 React,包括 JSX; here's how to do one.
  • @T.J.Crowder 我实际上不知道如何在react 中这样做,所以我采用了正常的js 方式^_____^

标签: javascript html css reactjs


【解决方案1】:

你是对的。当我们从逻辑上思考时,您需要保留旧元素。像这样;

let prevElement;
const hash = window.location.hash;

if (hash) {
  if (prevElement) {
    prevElement.classList.remove("active");
  }

  const id = symbolRemover(hash) + "__list";
  const element = document.getElementById(id);
  element.classList.add("active");
  prevElement = element;
}

但你应该在这里做一些空检查,例如

如果元素未定义怎么办?然后你得到一个错误,所以你可以这样更新:

  const element = document.getElementById(id);

  if (element) {
    ...
  }

这个答案可能不是一个完美匹配的答案。但我希望你明白了

【讨论】:

    猜你喜欢
    • 2022-12-05
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-20
    • 1970-01-01
    • 2021-06-29
    • 2014-02-22
    相关资源
    最近更新 更多