在 REACT JS 中动态添加活动类到多级侧边栏菜单

Son*_*xon 10 javascript reactjs react-router

我目前正在 REACT 中创建一个多级侧边栏菜单,我想<li>在当前路由处于活动状态时动态地将活动类添加到父级。

下面的代码是我为单个菜单执行此操作的方法。

<Route
  path={this.props.to}
  exact={this.props.activeOnlyWhenExact}
  children={({ match }) => (
    <li className={match ? "active" : ""}>
      <Link to={this.props.to} activeClassName="active">
        <span className="sidebar-mini-icon">
          <i className={this.props.icon}></i></span>
          {this.props.label}
      </Link>
    </li>
  )}
/>
Run Code Online (Sandbox Code Playgroud)

现在我想知道如何使用多级菜单来做到这一点。我的菜单看起来像这样;

在此输入图像描述

如您所见,只有菜单具有活动类。这是我的多级菜单代码:

<Route
  path={this.props.to}
  exact={this.props.activeOnlyWhenExact}
  children={({ match }) => (
  <li>
    <a data-toggle="collapse" href="#Collapse">
      <span className="sidebar-mini-icon">
        <i className={this.props.icon}></i>
      </span>
      <span className="sidebar-normal">
        {this.props.name}
        <b className="caret"></b>
      </span>
    </a>
    <div class="collapse" id="Collapse">
       <ul className="nav">
         {this.props.children}
       </ul>
    </div>
  </li>
  )}
/>
Run Code Online (Sandbox Code Playgroud)

我正在使用反应路由器。任何帮助将不胜感激。谢谢。

Jem*_*alo 0

我的第一反应是添加className={match ? "active" : ""}到 Parent li,但既然你在问这个问题,我假设你已经尝试过了。

您可以深入研究孩子们的道具,看看他们中是否有人拥有该match道具(或任何其他表明他们处于活动状态的道具)。下面的函数可以match从孩子那里找到道具。

const childMatch = children => {
  if (!children) { return false }
  if (Array.isArray(children)) {
    return children.reduce(
      (acc, child) => acc || Boolean(child.props.match),
      false
    )
  }
  return Boolean(children.props.match)
}
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样使用它className={childMatch(this.props.children) ? "active" : ""}

如果您要寻找的 prop 位于子树的较深处,您当然可以深入挖掘。您可以找到孙子作为child.props.children