我有一个对象数组,其中包含导航栏的密钥对值 链接,我已将数组映射到列表并成功渲染, 但是当我尝试将类添加到仅活动链接时,它正在添加 类所有链接项。
想知道我要去哪里错了吗?
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;
答案 0 :(得分:3)
您可以保留一个状态,例如: activeLink
存储活动链接的ID,您可以使用该ID将类应用于render方法中的活动链接。
示例
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>
答案 1 :(得分:1)
问题是这行代码:
const currentClass = document.getElementsByClassName('side_nav_item');
正在使用HTML
CSS类抓取您所有的side_nav_items
元素,在您的情况下,这就是您所有的侧面导航链接。您可能要使用:
let element = document.getElementById(id);
只是获得由id
标识的被单击的侧面导航元素。然后,您可以使用element.classList.add('active_item');
将active_item
css类添加到所选的侧面导航项。
希望有帮助!