首页 > web前端 > js教程 > 正文

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

Patricia Arquette
发布: 2024-10-23 18:44:31
原创
454 人浏览过

How Can I Pass Props to Handler Components in React Router?

将 props 传递给 React Router 中的处理程序组件

在 React Router 中,将 props 传递给处理程序组件是一个常见的需求。考虑以下结构:

var Dashboard = require('./Dashboard');
var Comments = require('./Comments');

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

var routes = (
  <Route path="/" handler={Index}>
    <Route path="comments" handler={Comments}/>
    <DefaultRoute handler={Dashboard}/>
  </Route>
);

ReactRouter.run(routes, function (Handler) {
  React.render(<Handler/>, document.body);
});
登录后复制

直接传递道具

传统上,您可以将道具直接传递到评论组件,如下所示:

<Comments myprop="value" />
登录后复制

通过 React Router 传递 Props

但是,在 React Router 中,props 必须通过 Route 的组件 prop 传递。有两种方法可以做到这一点:

1。使用包装组件

创建一个包装处理程序组件的包装组件:

var RoutedComments = React.createClass({
  render: function () {
    return <Comments {...this.props} myprop="value" />;
  }
});
登录后复制

然后,在路由中使用 RoutedComments 组件而不是 Comments 组件:

<Route path="comments" handler={RoutedComments}/>
登录后复制

2.使用带有路由属性的类组件

定义一个继承自 React.Component 的类组件并使用组件属性:

class Index extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <h1>
        Index - {this.props.route.foo}
      </h1>
    );
  }
}

var routes = (
  <Route path="/" foo="bar" component={Index}/>
);
登录后复制

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

来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!