javascript - 如何被点击 li 高亮显示
问题描述
我正在尝试访问key={1}
我的 li 上的元素。我想要实现的是将 activeItem 设置为 State,以便稍后将其与单击的项进行比较。我他们是一样的,我想为那个元素添加一个活动类。但是我找不到将密钥传递给我的 handleClick 函数的方法。
谢谢你的帮助。
import Link from 'next/link';
class Navbar extends React.Component {
state = { activeItem: null}
handleClick = (e) => {
};
render() {
console.log(this.state)
return (
<nav className="main-nav">
<ul>
<li>
<a href="/">Home</a>
</li>
<li>
<a href="#">Kategories
<span className="arrow">▼</span>
</a>
<ul className="submenu">
<li
onClick={this.handleClick}
key={1}
>
<Link href={`/news?cat=sport`} ><a>Sport</a></Link>
</li>
<li>
<Link href={`/news?cat=health`}><a>Health</a></Link>
</li>
</ul>
</li>
</ul>
<style jsx>{`
.main-nav {
font-family: "Lato";
font-style: normal;
font-weight: 400;
z-index:100;
-webkit-box-shadow: 1px 3px 23px -8px rgba(0,0,0,0.75);
-moz-box-shadow: 1px 3px 23px -8px rgba(0,0,0,0.75);
box-shadow: 1px 3px 23px -8px rgba(0,0,0,0.75);
}
.main-nav a {
color: #000;
background: #fff;
height: 50px;
font-family: lato;
font-weight: bold;
display: flex;
align-items: center;
justify-content: center;
text-decoration: none;
transition: background 0.4s;
}
.main-nav a:hover {
background: #b4d455;
color: #fff;
border: 1px solid #000;
}
.main-nav a:hover .arrow{
color: #fff;
transform: rotate(0);
}
.main-nav ul {
list-style: none;
display: flex;
}
.main-nav li {
width: 100%;
text-align: center;
position: relative;
}
.main-nav li:hover .submenu > li {
display: block;
flex-direction: column;
top: 0px;
}
.submenu li {
display: none;
position: absolute;
top: 0px;
}
.submenu {
display: flex;
flex-direction: column;
position: absolute;
width: 100%;
}
.submenu li {
position: relative;
}
.submenu li:hover .submenu-2 li {
display: block;
}
.arrow {
margin-left: 8px;
color: #000;
font-size: 10px;
transform: rotate(90deg);
}
.active {
background-color: red;
}
`}
</style>
</nav>
);
}
}
export default Navbar;
谢谢你的回答。有用 。但我不确定这是否是最好的方法。数据键目前不是动态的,我不确定如何获取三元中的值。
state = { activeItem: null}
handleClick = e => {
this.setState({ activeItem : e.currentTarget.dataset.key })
};
render() {
return (
<nav className="main-nav">
<ul>
<li>
<a href="/">Home</a>
</li>
<li>
<a href="#">Kategories
<span className="arrow">▼</span>
</a>
<ul className="submenu">
<li className={this.state.activeItem == 1 ? 'active' : ''}
onClick={this.handleClick}
data-key={1}
>
解决方案
推荐阅读
- c - 为什么使用三元运算符进行数组初始化是非法的?
- python - 我想发送带有超链接 URL 代码的消息
- java - 对两个文本文件使用余弦相似度
- css - 自定义 CSS 复选框和多行对齐刻度
- c# - 来自字节 [] 滞后的 Unity LoadImage
- git - 从以前的提交中获取更改 Archanist
- javascript - 在对象的原型上使用自定义 getter 定义属性是否可以接受?
- sql - 如何修复访问查询中的重复项
- javascript - HTML5/js 中十六进制数的输入掩码
- java - 错误:无法访问 com.facebook.imagepipeline.animated.base.AnimatedImage 的 AnimatedImage 类文件未找到