javascript - 当组件不等于 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>
解决方案
您可以签 props.history.location.pathname
入标头组件还确保将标头组件包装在withRouter
例如:
const Header = props => {
return <div className={props.history.location.pathname === '/anything' ? "YOUR_CLASS":""}>....</div>
}
export default withRouter(Header)
推荐阅读
- java - 来自 Java 和 Php 的 https 链接的不同输出
- python - 散景堆积条形图
- python - Web Scraping - ResultSet 对象没有属性“findAll”
- shiny - 在 Shiny 应用程序中显示数据框的子集
- java - 如何在 JavaFX 中使用 lambda 表达式调用动作事件的方法
- java - 为什么 wait() 和 notify() 在这个程序中不起作用?
- javascript - Pug JS:如何将输入的值保留在输入字段中,而不是在验证后清除表单
- hibernate - 在 Spring Boot 中使用 Junit 测试 Hibernet 的问题
- crud - WebFlux:为什么我需要在 CRUD 中使用 flatMap
- mysql - 如何使用 MySQL 表中的其他列在列中进行计算?