由于react-router没有为链接或li添加活动类,我希望将活动链接保持在菜单状态。当我记录this.state.activeLink时,我得到正确的值,但由于某种原因,类'activeLink'没有添加到li。为什么是这样?当我记录它时,isActive()正确返回true或false,但仍然没有将类添加到li中。这是怎么回事?
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import logo from '../images/logo.png';
export default class Navbar extends Component {
constructor(props){
super(props);
this.state = { activeLink : '' };
this.setActive = this.setActive.bind(this);
}
setActive(event){
this.setState({ activeLink: event.target.id });
}
isActive(link){
console.log('isActive:', link == this.state.activeLink);
link == this.state.activeLink ? 'activeLink' : '';
}
render(){
return (
<div className="header">
<div className="row">
<div className="header-left">
<div className="logo">
<img src={logo} alt=""/>
</div>
<div className="header-title">Physical Twist</div>
<div className="menu">
<ul className="nav">
<li className={this.isActive('home')}><Link to="/" id="home" onClick={this.setActive}>Home</Link></li>
<li className={this.isActive('store')}><Link to="/store" id="store" onClick={this.setActive}>Store</Link></li>
<li className={this.isActive('catalogue')}> <Link to="#" id="catalogue" onClick={this.setActive}>Catalogue</Link></li>
<li className={this.isActive('contact')} ><Link to="#" id="contact" onClick={this.setActive}>Contact</Link></li>
</ul>
</div>
</div>
</div>
</div>
);
};
}
答案 0 :(得分:1)
isActive
没有返回任何内容。
isActive(link){
link == this.state.activeLink ? 'activeLink' : '';
}
应该是
isActive(link){
return link == this.state.activeLink ? 'activeLink' : '';
}
答案 1 :(得分:1)
由于您忘记在return
功能中添加isActive()
,请使用此功能:
isActive(link){
console.log('isActive:', link == this.state.activeLink);
return link == this.state.activeLink ? 'activeLink' : '';
}