[英]React Router and navigation buttons
I have navigation buttons (the typical left panel dashboard variety) that use Links to load pages in the main content area. 我有导航按钮(典型的左面板仪表板种类),使用链接加载主要内容区域中的页面。
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>
);
}
});
When a button gets clicked, I need to change its state to selected so I can add a CSS class and change its background color. 单击一个按钮时,我需要将其状态更改为选中状态,以便添加CSS类并更改其背景颜色。
What is the right way to do this with React Router? 使用React Router执行此操作的正确方法是什么? I could just have the buttons manage their own selected state, but that will break down because sometimes the navigation (the button click) will be prevented and aborted because the user hasn't saved changes on the current page.
我可以让按钮管理他们自己选择的状态,但是这会分解,因为有时导航(按钮点击)将被阻止和中止,因为用户没有在当前页面上保存更改。
Link
has a property called activeClassName
which you can use. Link
有一个名为activeClassName
的属性,您可以使用它。 Whatever the value is specified that className is being added to the Link
component when it's active. 无论指定什么值,className在激活时都会添加到
Link
组件。
You also can use the history
which is available in props
if it's a route component or get the history
of context
for other components and use this.props.history.isActive('/pathToCheck')
您还可以使用
props
可用的history
(如果它是路径组件)或获取其他组件的context
history
并使用this.props.history.isActive('/pathToCheck')
Example: 例:
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>
you can use the same with use of context
instead of History
mixin. 您可以使用相同的
context
而不是History
mixin。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.