React Router如何在路由更改时更改组件中元素的类名?

时间:2017-01-01 22:53:57

标签: reactjs react-router

我有以下方式的路线:

<Route path="" component={Sidebar}>
    <Route path="pages/about" component={PageFactory}" />
    <Route path="news" component={NewsFactory}" />
</Route>

现在我想在路由更改时向侧栏组件添加一个类。因此,如果route变为“/ pages / about”,我想将“is-open”className添加到Sidebar组件中的元素。如果route变为“/”,我想从Sidebar组件中的元素远程调用className。

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

每个组件都有一些有用的属性。

在侧边栏组件中,您可以执行以下操作:

const Sidebar = React.createClass({
   render() {
     let { location:{pathname, params, query} } = this.props; // router props
   }
});

然后,您可以检测pathname是否about然后执行is-open