首页  >  文章  >  web前端  >  如何将 Props 传递给 React Router 中的处理组件?

如何将 Props 传递给 React Router 中的处理组件?

Patricia Arquette
Patricia Arquette原创
2024-10-24 00:02:02177浏览

How to Pass Props to Handled Components in React Router?

在 React Router 中将 props 传递给已处理的组件

在使用 React Router 的 React.js 应用程序中,经常需要将 props 传递给已处理的组件。为了实现这一点,有几种方法可以考虑:

一种简单的方法是用一个新组件包装已处理的组件,该新组件获取所需的 props 并根据需要将它们传递下来:

<code class="javascript">var CommentsWrapper = React.createClass({
  render: function () {
    return <Comments myprop="value" />;
  }
});</code>

这样,您就可以使用 CommentsWrapper 作为所需路由的处理程序:

<code class="javascript">var routes = (
  <Route path="/" handler={Index}>
    <Route path="comments" handler={CommentsWrapper}/>
    <DefaultRoute handler={Dashboard}/>
  </Route>
);</code>

但是,如果您需要将 props 传递给多个已处理的组件,这种方法可能会变得笨拙。在这种情况下,更灵活的方法是在路由配置中使用 component 属性,它允许您直接将 props 传递给处理的组件:

<code class="javascript">var routes = (
  <Route path="/" component={Index}/>
);

var Index = React.createClass({
  render: function () {
    return (
      <div>
        <header>Some header</header>
        <RouteHandler myprop="value" />
      </div>
    );
  }
});</code>

通过这种方法,您可以将 props 直接传递给无需包装器的评论组件:

<code class="javascript"><Route path="comments" component={Comments}/></code>

以上是如何将 Props 传递给 React Router 中的处理组件?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn