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

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

Mary-Kate Olsen
发布: 2024-10-24 03:11:02
原创
345 人浏览过

How to Pass Props to Handler Component in React Router?

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

在使用 React Router 的 React.js 应用程序中,可能存在传递特定属性的情况子组件是必要的。例如,考虑以下结构:

<code class="javascript">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);
});</code>
登录后复制

目标是将属性传递到 Comments 组件。通常,这可以直接在组件声明中实现。然而,对于 React Router,需要一种替代方法。

一个选择是使用包装器组件。这将涉及创建一个单独的组件来包装 Comments 组件并传递所需的 props。这是一个示例:

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

// Then in the routes definition:

var routes = (
  <Route path="/" handler={Index}>
    <Route path="comments" handler={CommentsWithProps}/>
    <DefaultRoute handler={Dashboard}/>
  </Route>
);</code>
登录后复制

另一种不使用包装组件的方法是修改 Index 组件:

<code class="javascript">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}/>
);</code>
登录后复制

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

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