首页 > 解决方案 > 如何突出显示活动导航栏段落

问题描述

有反应组件 - 导航栏:

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>

标签: javascriptreactjs

解决方案


您可以像这样简单地添加基于道具的类:

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


推荐阅读