javascript 如何在ReactJS中为点击项添加活动类

ifmq2ha2  于 2023-01-08  发布在  Java
关注(0)|答案(3)|浏览(122)

我有一个包含导航栏链接的密钥对值的对象数组,我已经将数组Map到列表并成功渲染它,但当我尝试仅向活动链接添加类时,它将类添加到所有链接项。
想知道我哪里做错了吗?

import React, { Component } from "react";
import { Link } from "react-router-dom";

class SideNavbar extends Component {
  constructor(props) {
    super(props);
    this.state = [
      { id: 1, name: "Link1", to: "/cms", className: "side_nav_item" },
      { id: 2, name: "Link2", to: "/cms", className: "side_nav_item" },
      { id: 3, name: "Link3", to: "/cms", className: "side_nav_item" },
      { id: 4, name: "Link4", to: "/cms", className: "side_nav_item" }
    ];
  }

  handleClick = () => {
    const currentClass = document.getElementsByClassName("side_nav_item");
    for (let i = 0; i < currentClass.length; i++) {
      currentClass[i].classList.toggle("active_item");
      console.log(currentClass[i]);
    }
  };
  render() {
    const navLinks = this.state.map(link => {
      return (
        <div key={link.id}>
          <ul>
            <li onClick={this.handleClick} className={link.className}>
              <Link to={link.to}>{link.name}</Link>
            </li>
          </ul>
        </div>
      );
    });
    return <div>{navLinks}</div>;
  }
}

export default SideNavbar;
w8rqjzmb

w8rqjzmb1#

您可以保留一个名为activeLink的状态块,用于存储活动链接的id,以便在render方法中将类应用于活动链接,而不是尝试手动操作DOM。

    • 示例**
class SideNavbar extends React.Component {
  state = {
    links: [
      {
        id: 1,
        name: "Link1",
        to: "/cms",
        className: "side_nav_item"
      },
      {
        id: 2,
        name: "Link2",
        to: "/cms",
        className: "side_nav_item"
      },
      {
        id: 3,
        name: "Link3",
        to: "/cms",
        className: "side_nav_item"
      },
      {
        id: 4,
        name: "Link4",
        to: "/cms",
        className: "side_nav_item"
      }
    ],
    activeLink: null
  };

  handleClick = id => {
    this.setState({ activeLink: id });
  };

  render() {
    const { links, activeLink } = this.state;

    return (
      <div>
        {links.map(link => {
          return (
            <div key={link.id}>
              <ul>
                <li
                  onClick={() => this.handleClick(link.id)}
                  className={
                    link.className +
                    (link.id === activeLink ? " active_item" : "")
                  }
                >
                  {link.name} {link.id === activeLink && "active!"}
                </li>
              </ul>
            </div>
          );
        })}
      </div>
    );
  }
}

ReactDOM.render(<SideNavbar />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>
0yg35tkg

0yg35tkg2#

问题在于这一行代码:
第一个月
正在使用side_nav_items CSS类获取所有HTML元素,在 * 您的情况下,这是您的所有侧导航链接 *。您可能需要使用:
let element = document.getElementById(id);
来获取被点击的侧边导航元素,该元素被标识为id。然后,您可以使用element.classList.add('active_item');active_item css类添加到所选的侧边导航项。
希望能有所帮助!

7hiiyaii

7hiiyaii3#

一段时间前,我一直在为这个问题而挣扎,这个解决方案对我很有效。
从“react-router-dom”导入{ useLocation };
常量路径名= useLocation().路径名;
然后在Link元素中可以简单地执行className={pathName === link.to ? 'active_item' : ''}

相关问题