javascript 首次单击时未添加类

aiazj4mn  于 2023-01-29  发布在  Java
关注(0)|答案(1)|浏览(95)

我试图动态添加类'活动'的按钮,只有当他们被点击。但它不工作,当我第一次点击第二个按钮。

const aboutText:string = 'Lorem ipsum dolor';
const [text, setText] = useState<string>('');
const btnAbout = document.getElementById('aboutDescription');
const btnExperience = document.getElementById('experienceDescription');

const handleClickAbout = () => {
    setText('aboutDescription');
    btnAbout?.classList.add('active');
    btnExperience?.classList.remove('active');
}

const handleClickExperience = () => {
    setText('experienceDescription');
    btnExperience?.classList.add('active');
    btnAbout?.classList.remove('active');
}

return (

    <button className='btn-info active' onClick={handleClickAbout} id='aboutDescription'> About </button>
    <button className='btn-info' onClick={handleClickExperience} id='experienceDescription'> Experience </button>

  <div className='description-right'>
      {(text === 'aboutDescription' || text ==='') && aboutText}
      {text === 'experienceDescription' && 'Experience'}
  </div>
)

开头的第一个按钮有活动类,第一次点击体验按钮时,活动类没有添加,第二次点击时才添加。我能用某种方法解决这个问题吗?

r1wp621o

r1wp621o1#

这不是你使用react的方式。通常当你使用getElementByIdclassList时,它意味着你做错了什么
让react为您操作DOM
示例:

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

export default function App() {
  const aboutText = "Lorem ipsum dolor";
  const [text, setText] = useState("");
  const isAboutActive = text === "aboutDescription" || text === "";
  const isExperienceActive = text === "experienceDescription";

  const handleClickAbout = () => {
    setText("aboutDescription");
  };

  const handleClickExperience = () => {
    setText("experienceDescription");
  };

  return (
    <>
      <button
        className={clsx("btn-info", isAboutActive && "active")}
        onClick={handleClickAbout}
      >
        About
      </button>
      <button
        className={clsx("btn-info", isExperienceActive && "active")}
        onClick={handleClickExperience}
      >
        Experience
      </button>

      <div className="description-right">
        {isAboutActive && aboutText}
        {isExperienceActive && "Experience"}
      </div>
    </>
  );
}

相关问题