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

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

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-10-24 03:11:02345浏览

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中文网其他相关文章!

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