javascript - 如何突出显示活动导航栏段落
问题描述
有反应组件 - 导航栏:
import React from 'react';
function Navbar(props) {
return (
<nav className="navbar">
<a data-id="first" href="/">/</a>
<a data-id="second" href="/link">/link</a>
</nav>
);
}
export default Navbar;
<Navbar active="second" />
根据props.active
,您如何选择活动元素?
在纯js中,我将创建一个链接对象并使用循环生成导航栏:
const objOfLinks = {
"1": {
text: "some text",
href: "/"
},
"2": {
text: "some text",
href: "/link"
}
}
function nav(obj, active = "1") {
let nav = document.createElement('nav');
for (item in obj) {
const a = document.createElement('a');
a.textContent = obj[item].text;
a.href = obj[item].href;
if (item == active) {
a.style.color = 'red';
}
nav.appendChild(a);
}
return nav;
}
document.querySelector('div').appendChild(nav(objOfLinks, 2));
<div></div>
解决方案
您可以像这样简单地添加基于道具的类:
function Navbar(props) {
return (
<nav className="navbar">
<a
data-id="first"
className={props.active === "first" ? "active" : ""}
href="/"
>
First
</a>
<a
data-id="second"
className={props.active === "second" ? "active" : ""}
href="/link"
>
Second
</a>
</nav>
);
}
这是演示:https ://codesandbox.io/s/bitter-forest-5edu1?file=/src/App.js:51-428
推荐阅读
- docker - .htaccess 重定向页面未找到到不同的端口(apache docker 容器)
- android - Ionic android 应用程序立即崩溃
- linux - 无法使用 samba 共享访问 mhddfs 虚拟挂载
- rust - 隐藏两个特征共享的关联类型
- loops - 遍历 Golang 中的结构并打印设置的值
- ios - .fileExporter 的使用
- angular - Docker 容器正在构建但未在 localhost 上显示项目的前端页面
- wpf - 将数据添加到 DataGrid 对象后,不会重新调整列
- mysql - JPA Query 用于在所需输出中使用单列 2 列
- c# - 在 Windows 身份验证中,如果在 http://abc.localhost/myweb/ 等 URL 中使用子域(abc),如何允许用户