我使用es6
,twitter bootstrap
和react-router 1.0.0-rc3
。我想创建一个导航栏并添加到li
元素类active
。
我尝试使用history对象的isActive
方法。
var RouterPropTypes = require('react-router').PropTypes;
LinkWrapper组件
export class LinkWrapper extends React.Component{
constructor(props, context) {
super(props, context);
}
render() {
console.log(this.props.to);
console.log(this.props.query);
let isActive = this.context.history.isActive(this.props.to, this.props.query);
let className = isActive ? 'active' : '';
return (<li className={className}>
<CustomersIcon />
<Link {...this.props}/>
</li>);
}
}
LinkWrapper.contextTypes = {
history: RouterPropTypes.history
};
导航栏组件
export class NavBar extends React.Component {
constructor(props, context) {
super(props, context);
}
componentDidUpdate() {
console.log('NavBar - componentDidUpdate');
}
render() {
return (
<nav className="navbar navbar-default">
<div className="collapse navbar-collapse" id="main-navbar-collapse">
<ul className="nav navbar-nav">
<LinkWrapper href="customers" />
</ul>
</div>
</nav>
);
}
}
NavBar.contextTypes = {
history: RouterPropTypes.history
}
在线this.context.history.isActive
我收到错误:
Uncaught TypeError: Cannot read property 'match' of undefined
因为this.props.to
和this.props.query
是'undefined'
。
我还尝试使用History Mixin在es5中创建LinkWrapper组件,但是this.props.to和this.props.query仍未定义&#39;。
var Router = require('react-router');
var { Route, DefaultRoute, RouteHandler, Link, History } = Router;
const Tab = React.createClass({
mixins: [ History ],
render() {
console.log(this.props.to);
console.log(this.props.query);
let isActive = this.history.isActive(this.props.to, this.props.query);
let className = isActive ? 'active' : '';
return (<li className={className}>
<CustomersIcon />
<Link {...this.props}/>
</li>);
}
});
答案 0 :(得分:2)
使用有效的班级名称
<Link ... activeClassName="active" />
如果你想使用this.props.history,那么你必须设置历史
// create browser history for navigating
import createBrowserHistory from 'history/lib/createBrowserHistory';
let history = createBrowserHistory();
然后将历史道具添加到路由器
<Router history={history}>
<Route component={App} path="/">
<Route component={indexView} path="/index" />
</Route>
</Router>
然后在像indexView这样的组件中你可以做到这一点
this.props.history.isActive('/someroute')