【问题标题】:React Router and navigation buttonsReact 路由器和导航按钮
【发布时间】:2015-11-26 14:27:31
【问题描述】:

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

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>
    );
  }

});

当一个按钮被点击时,我需要将其状态更改为选中,这样我就可以添加一个 CSS 类并更改其背景颜色。

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

【问题讨论】:

标签: javascript reactjs react-router


【解决方案1】:

Link 有一个名为activeClassName 的属性,您可以使用它。无论指定什么值,当 className 处于活动状态时,它都会被添加到 Link 组件中。

如果它是路由组件,您也可以使用props 中提供的history,或者将contexthistory 用于其他组件并使用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>

您可以使用 context 而不是 History mixin。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-13
  • 1970-01-01
  • 2016-11-14
  • 2017-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多