React-router isActive方法不起作用

时间:2015-11-02 10:27:08

标签: javascript reactjs react-router

我使用es6twitter bootstrapreact-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.tothis.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>);
  }
});

1 个答案:

答案 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')