基于 React Router 中的 slug 的条件处理程序? [英] Conditional handler based on slug in React Router?
问题描述
我是新手.我正在使用 React Route,我想知道是否可以根据传递给路由的 slug 执行不同的处理程序.
I am new to react. I am using React Route and I would like to know if it's possible to execute a different handlers based on a slug passed to the route.
例如我有以下路线:
<Route name="page" path={'/:slug'} />
是否可以根据该 slug 动态设置要执行的处理程序?
Is it possible to dynamically set the handler to be executed based on that slug?
我在他们的 API/示例中找不到任何内容.
I couldn't find anything on their API/Examples.
提前致谢!
推荐答案
请记住,React/JSX 为您提供了 JavaScript 的全部功能.这意味着您的路由处理程序组件可以做任何它想做的事情——包括有条件地渲染子级.像这样的东西可能会起作用(我没有运行过,所以认为它是伪代码):
Remember that React/JSX gives you the full power of JavaScript. That means your route handler component can do whatever it wants--including rendering children conditionally. Something like this may work (I haven't run this, so consider it pseudocode):
注意:我使用的是 0.13 语法,因为这似乎是您使用的版本.
var slugsToHandlers = {
'about': AboutPage,
'jobs': JobsPage,
};
var SlugRouteComponent = React.createClass({
contextTypes: {
router: React.PropTypes.func
},
render: function() {
var slug = this.context.router.getCurrentParams().slug;
var Handler = slugsToHandlers[slug] || NotFundPage;
return <Handler {...this.props} />;
}
});
// ...
<Route name="page" path="/:slug" handler={SlugRouteComponent} />
如果需要,您也可以单独列出每条路线:
You could also, if you wanted, list each route individually:
<Route name="aboutPage" path="/about" handler={AboutPage} />
<Route name="jobsPage" path="/jobs" handler={JobsPage} />
<Route name="page" path="/:slug" handler={NotFoundPage} />
这篇关于基于 React Router 中的 slug 的条件处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!