我有一个 React 和 React-Router 应用程序,它使用 2 条嵌套路由来传递 3 条总路由:/、/about、/contact。当我单击“链接”转到每条路线时,位于父 route 的导航栏上的选项卡会更改样式并显示其事件状态,我相信这是一些 Bootstrap 魔法。问题是当我访问/about 或/contact 时,导航选项卡未激活。我是新手,但我想我需要将 style 属性绑定(bind)到检查路由属性或组件状态的条件。我不确定如何执行此操作,我们将不胜感激。
导航所在的简化布局
export default class Layout extends React.Component {
render() {
return (
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><Link to="/about">About</Link></li>
<li><Link to="/contact">Contact</Link></li>
</ul>
</div>
)}}
在 < li > 我需要类似 class={if this.props.children == About, class=active, class=""} 的地方
渲染路线
render((
<Router history={hashHistory}>
<Route path="/" component={Layout}>
<Route path="/about" component={About}/>
<Route path="/contact" component={Contact}/>
</Route>
</Router>
), document.getElementById('app'))
是的,如上所述,li 需要检查 Layouts props.children 是否为 null,或者它是否是 about 或 contact。如果它是 react 组件,我真的不确定如何比较 this.props.children 的值
感谢所有先进!!!
最佳答案
按照我们在评论中的对话,这就是您获得 active
的方式<li>
上的类(class)名称标签:
注意:我假设您使用的是 React Router v1.0.x,我强烈建议您使用最新版本 - 2.0,请参阅 Upgrade Guides
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>
如果您使用的是 ES6 类,您会以非常相似的方式进行操作,但您需要“拉”history
而不是使用混合宏。来自上下文(here is how to do it - 同样,这是在 React Router v1.0.x 分支上)。
关于javascript - 如果当前在该 route ,则将导航选项卡样式类设置为事件状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35735196/