B. *_*wok 4 javascript hyperlink toggle reactjs
以下React.js代码使用两个名为“ about”和“ project”的链接来渲染导航栏。在页面加载时,“关于”链接处于活动状态,并显示为红色。单击另一个链接后,导航栏的状态将设置为“项目”,“链接”样式将重新设置,并且“项目”将显示为红色。
我通过在两个链接标记上附加一个单击处理程序,并将active状态设置为event.target.innerHTML的名称来实现。
我是新来的反应者,我认为这是解决该问题的非常冗长的方法。我知道有一个activeClassName属性可以传递给react-router链接,但是我想要一种不使用它的方法。
import React, { Component } from 'react'
import { Link, Route } from 'react-router'
export default class Navbar extends Component {
constructor() {
super();
this.state = {
active: 'about'
}
this._handleClick = this._handleClick.bind(this);
}
_handleClick(e) {
this.setState({
active: e.target.innerHTML
});
}
render() {
let aboutStyle;
let projectStyle;
if (this.state.active === 'about') {
aboutStyle = { color: '#ff3333' };
projectStyle = {};
} else {
aboutStyle = {};
projectStyle = { color: '#ff3333' };
}
return (
<div className='navbar'>
<Link to='/'><h2>BK //</h2></Link>
<div className='menu'>
<Link style={aboutStyle} onClick={this._handleClick} to='about'>about</Link>
<Link style={projectStyle} onClick={this._handleClick} to='projects'>projects</Link>
</div>
</div>
)
}
}
Run Code Online (Sandbox Code Playgroud)
Yur*_*rin 23
在这一天,您可以使用 NavLink react-router-dom
。此对象支持属性为activeClassName
、activeStyle
或isActive
(对于函数)。
import { NavLink } from 'react-router-dom';
<NavLink to='about' activeClassName="active">about</NavLink>
// Or specifing active style
<NavLink to='about' activeStyle={{color: "red"}}>about</NavLink>
// If you use deep routes and you need an exact match
<NavLink exact to='about/subpath' activeClassName="active">about</NavLink>
Run Code Online (Sandbox Code Playgroud)
有关更多选项,请阅读文档:https : //reacttraining.com/react-router/web/api/NavLink
也许稍微不那么冗长...在伪代码中
const menuItems = [
'projects',
'about',
];
class MenuExample extends React.Component {
_handleClick(menuItem) {
this.setState({ active: menuItem });
}
render () {
const activeStyle = { color: '#ff3333' };
return (
<div className='menu'>
{menuItems.map(menuItem =>
<Link
style={this.state.active === menuItem ? activeStyle : {}}
onClick={this._handleClick.bind(this, menuItem)}
>
{menuItem}
</Link>
)}
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)