首页 > 解决方案 > 当组件不等于 home 时如何更改类而不是在 react.js 的头组件中添加类?

问题描述

当路由不在家时,我想在标题组件中添加一个类。我的代码是:

应用程序.js

<BrowserRouter>
  <Header />
  <Route exact path="/" component={Home}/>
  <Route exact path="/shop" component={Shop}/>
  <Route exact path="/contact" component={Contact}/>
  <Footer />
</BrowserRouter>

Header.js 组件代码:

 <div className="all-category (here add-class when route is not equal to home)">
  <h3 className="cat-heading"><i className="fa fa-bars" aria-hidden="true"></i>CATEGORIES</h3>
   <ul className="main-category">
    <li><a href="#">New Arrivals <i className="fa fa-angle-right" aria-hidden="true"></i></a>
      <ul className="sub-category">
         <li><a href="#">accessories</a></li>
         <li><a href="#">best selling</a></li>
         <li><a href="#">top 100 offer</a></li>
       </ul>
    </li>
   </ul>
  </div>

标签: javascriptreactjs

解决方案


您可以签 props.history.location.pathname入标头组件还确保将标头组件包装在withRouter 例如:

const Header = props => {
  return <div className={props.history.location.pathname === '/anything' ? "YOUR_CLASS":""}>....</div>
}

export default withRouter(Header)

推荐阅读