[英]How to change styles of a parent element of a <NavLink> tag in React.js?
I want to change the list-items' background-color property, when the chosen NavLink is active. 当选定的NavLink处于活动状态时,我想更改列表项的background-color属性。 From the docs I learned, that for adding an additional class to a NavLink , when it is active, I can use activeClassName prop, for making what I want, I need a parent selector in css, which don't exist.
从我学到的文档中,可以在NavLink处于活动状态时向其添加一个附加类,可以使用activeClassName属性来实现所需的功能,而在CSS中需要一个父选择器,而该选择器不存在。
How to choose the parent element of the NavLink tag, when it has an active class ? NavLink标签具有活动类时,如何选择其父元素?
I need the green background only on the list-item with an active child NavLink. 我仅在具有活动子NavLink的列表项上需要绿色背景。
<ul className="navbar-nav"> <li className="navItem"> <NavLink className="navlink text-dark" activeStyle={{color: "#fff !important"}} to="/" exact>about</NavLink> </li> <li className="navItem"> <NavLink className="navlink text-dark" activeStyle={{color: "#fff !important"}} to="/services">services</NavLink> </li> <li className="navItem"> <NavLink className="navlink text-dark" activeStyle={{color: "#fff !important"}} to="/contacts">contacts</NavLink> </li> </ul>
The most straight forward way would probably be to apply a state to your parent element to achieve this effect, which ie could represent the name of a CSS class for your parent. 最直接的方法可能是将状态应用于父元素以实现此效果,即可以表示父CSS类的名称。 You can change this state depending on the active route or the clicked item to apply a new CSS class.
您可以根据活动路线或单击的项目来更改此状态,以应用新的CSS类。
See working example here 在这里查看工作示例
Your parent class could look like this: 您的父类可能如下所示:
import React from 'react'
import NavLink from './NavLink'
class Navbar extends React.Component {
constructor(props) {
super(props)
this.state = {
navbarClass: "navbar"
}
}
setBgClass (title) {
this.setState({
navbarClass: `navbar navbar-${title}`
})
}
render() {
return (
<div className={this.state.navbarClass}>
<NavLink
className="nav-item"
onClick={() => this.setBgClass('about')}
href='/about/'>
About
</button>
<NavLink
className="nav-item"
onClick={() => this.setBgClass('services')}
href='/services/'>
Services
</button>
<NavLink
className="nav-item"
onClick={() => this.setBgClass('contact')}
href='/contact/'>
Contact
</button>
</div>
);
}
}
export default Navbar
After that you only have to define appropriate CSS classes in your components stylesheet: 之后,您只需要在组件样式表中定义适当的CSS类即可:
.navbar-about { background: green; }
.navbar-services { background: blue; }
.navbar-contact { background: orange; }
NOTE: If you call actual routes within your application ie using react-router , you may want to change the state of your parent navbar depending on your active route on componentDidMount
instead of onClick
, since the component may remount when the route changes. 注意:如果您在应用程序中调用实际路由,即使用react-router ,则可能要根据
componentDidMount
而不是onClick
上的活动路由来更改父导航栏的状态,因为当路由更改时,组件可能会重新安装。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.