Mar*_*ina 8 reactjs react-router
关于主题如何在处理程序中获取路径名称?例如:
var routes = <Route handler={App} path="/">
<Route name="home" path="/home" handler={HomePage} />
<DefaultRoute handler={HomePage} />
</Route>
Router.run(routes, function(Handler, state) {
var params = state.params;
React.render(<Handler params={params}/>, document.body);
});
Run Code Online (Sandbox Code Playgroud)
现在假设我有一个这样的组件:
class HomePage extends React.Component {
render() {
return(<div>MyComponent</div>)
}
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能获得当前的路线名称?更具体一点,我想得到
name="home"
Run Code Online (Sandbox Code Playgroud)
属性来自
<Route name="home" path="/home" handler={HomePage} />
Run Code Online (Sandbox Code Playgroud)
SM7*_*M79 16
反应路由器之前0.13,您可以使用this.getRoutes()使用Router.State混入.
对于react-router 0.13,您也可以使用它:
var currentRoutes = this.context.router.getCurrentRoutes();
var lastRoute = currentRoutes[currentRoutes.length - 1];
console.log(lastRoute.name);
Run Code Online (Sandbox Code Playgroud)
对于react-router v2.0.x,您可以使用:
this.props.routes[this.props.routes.length-1]
Run Code Online (Sandbox Code Playgroud)
v4 已从代码库中删除了 JS API,这意味着上述方法将无法继续工作。
新方法是将 props 直接传递给正在渲染的组件,就像您通常使用 React 应用程序中的任何其他组件一样。
import React from 'react';
import { Match, Link, Miss } from 'react-router';
import DocumentMeta from 'react-document-meta';
import MainLayout from './Layouts/MainLayout';
import Homepage from './containers/Homepage/Homepage';
import Game from './containers/Game/Game';
import NotFound from './containers/NotFound/NotFound';
export const routes = {
homepage: {
exactly: true,
pattern: '/',
label: 'About React Lego',
component: Homepage
},
game: {
pattern: '/game',
label: 'Star Wars Trivia',
component: Game
}
};
const passPropsToRoute = ({ route, props }) => (
<span>
<DocumentMeta title={ route.title } />
<route.component {...props} routes={route.routes}/>
</span>
);
const matchWithSubRoutes = (key, i) => {
const route = routes[key];
return (<Match { ...route } key={ i } render={(props) => passPropsToRoute({ route, props })} />);
};
export function makeRoutes() {
return (
<MainLayout>
{Object.keys(routes).map(matchWithSubRoutes)}
<Miss title={`${siteTitle} - Page Not Found`} component={ NotFound } />
</MainLayout>
);
}
Run Code Online (Sandbox Code Playgroud)
要在示例应用程序中看到这一点,请查看具有react-router-4 分支的react-lego
| 归档时间: |
|
| 查看次数: |
16257 次 |
| 最近记录: |