Home >Web Front-end >JS Tutorial >How to Pass Props to Handler Components in React Router?
In React.js applications that leverage React Router, you may encounter scenarios where you need to pass props to specific handler components. Consider the following application structure:
<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>
To pass props to the Comments component, you typically use syntax like
One solution is to create a wrapper component that encapsulates both the handler component and the passed-in props:
<code class="javascript">// CommentWrapper var CommentWrapper = React.createClass({ render: function () { return <Comments {...this.props} />; } }); var routes = ( <Route path="/" handler={Index}> <Route path="comments" handler={CommentWrapper} myprop="value"/> <DefaultRoute handler={Dashboard}/> </Route> );</code>
Alternatively, you can leverage class components and the this.props.route object to access props passed to the parent route:
<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>
By setting the foo prop on the / route, you can access the prop later within the Index component using this.props.route.
The above is the detailed content of How to Pass Props to Handler Components in React Router?. For more information, please follow other related articles on the PHP Chinese website!