有一个反应组件 - 导航栏:
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 objOfArr = {
"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(objOfArr, 2));
<div></div>
作为这样的选项:示例。
好吧,或者使用类名库