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

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

Patricia Arquette
Patricia Arquette原创
2024-10-23 18:44:31455浏览

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

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