我正在为我的应用程序使用react,我有一个bootstrap导航栏菜单有三个选项卡。我想突出显示所选标签。
这是我的render()函数中的html代码。
<div className="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul className="nav navbar-nav navbar-left">
<li onClick={event => this.handleClick('tab1', event)} className={(this.state.activeTabClassName === "tab1") ? "active" : ""}><a href="#">HOME<span className="sr-only">(current)</span></a></li>
<li onClick={event => this.handleClick('tab2', event)} className={(this.state.activeTabClassName === "tab2") ? "active" : ""}><a href="/#/resources">RESOURCES</a></li>
<li onClick={event => this.handleClick('tab3', event)} className={(this.state.activeTabClassName === "tab3") ? "active" : ""}><a href="/#/contact">CONTACT</a></li>
</ul>
</div>
我使用handleClick函数来更改tabName:
handleClick(tabName, event) {
this.setState ({activeTabClassName : tabName});
//this.state.activeTabClassName = tabName;
}
我还在构造函数中将activeTabClassName的初始状态设置为'tab1':
constructor() {
super();
this.state = {activeTabClassName : "tab1"};
// this.handleClick = this.handleClick.bind(this);
}
整个Nav.js组件的代码
import React from 'react';
export default class Nav extends React.Component {
constructor() {
super();
this.state = {activeTabClassName : "tab1"};
}
handleClick(tabName, event) {
this.setState ({activeTabClassName : tabName});
}
render(){
return(
<nav className="navbar navbar-default" role="navigation">
<div className="container-fluid">
<div className="navbar-header">
<button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span className="sr-only">Toggle navigation</span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
</button>
<a className="navbar-brand navbar-utimg" href="https://www.xxx.xxxx" target="_blank">
<img alt="logo" src="/dist/assets/coe-logo.png"/>
</a>
</div>
<div className="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul className="nav navbar-nav navbar-left">
<li onClick={event => this.handleClick('tab1', event)} className={(this.state.activeTabClassName === "tab1") ? "active" : ""}><a href="#">HOME<span className="sr-only">(current)</span></a></li>
<li onClick={event => this.handleClick('tab2', event)} className={(this.state.activeTabClassName === "tab2") ? "active" : ""}><a href="/#/resources">RESOURCES</a></li>
<li onClick={event => this.handleClick('tab3', event)} className={(this.state.activeTabClassName === "tab3") ? "active" : ""}><a href="/#/contact">CONTACT</a></li>
</ul>
<form className="navbar-form navbar-right" role="search">
<div className="form-group">
<input type="text" className="form-control" placeholder="Search"/>
</div>
<button type="submit" className="btn btn-default">Submit</button>
</form>
</div>
</div>
</nav>
)
}
}
然而,它效果不佳。每次单击选项卡时,除非我再次单击它,否则它不会突出显示所选选项卡。为什么onClick函数不会立即改变状态?这个问题有更好的解决方案吗?
谢谢!