反应路由器和导航按钮

Set*_*eth 3 javascript reactjs react-router

我有导航按钮(典型的左面板仪表板种类),使用链接加载主要内容区域中的页面.

var {Link, History} = require('react-router');
var React = require('react');

var NavPanelButton = React.createClass({

  mixins: [History],

  click: function (e) {
    e.preventDefault();
    this.history.pushState(null, this.props.link);
  },

  render: function () {
    var iconClasses = `fa fa-${this.props.icon} fa-fw`;
    return (
      <div className="nav-panel-button" onClick={this.click}>
        <Link to={this.props.link}>
          <i className={iconClasses}/> {this.props.children}
        </Link>
      </div>
    );
  }

});
Run Code Online (Sandbox Code Playgroud)

单击一个按钮时,我需要将其状态更改为选中状态,以便添加CSS类并更改其背景颜色.

使用React Router执行此操作的正确方法是什么?我可以让按钮管理他们自己选择的状态,但这会分解,因为有时导航(按钮点击)将被阻止和中止,因为用户没有保存当前页面上的更改.

kno*_*ody 5

Link有一个activeClassName你可以使用的属性.无论指定了什么值,className Link在活动时都会添加到组件中.

如果它是路径组件,您也可以使用history可用props的那个history,或者获取context其他组件的使用this.props.history.isActive('/pathToCheck')

例:

import { Link, History } from 'react-router'

const Tab = React.createClass({
  mixins: [ History ],
  render() {
    let isActive = this.history.isActive(this.props.to, this.props.query)
    let className = isActive ? 'active' : ''
    return <li className={className}><Link {...this.props}/></li>
  }
})

// use it just like <Link/>, and you'll get an anchor wrapped in an `li`
// with an automatic `active` class on both.
<Tab href="foo">Foo</Tab>
Run Code Online (Sandbox Code Playgroud)

您可以使用相同context而不是Historymixin.