In a React.js application employing React Router, it's common to encounter the need to pass props to handled components. To achieve this, there are a few approaches to consider:
One simple approach is to wrap the handled component with a new component that takes the desired props and passes them down as needed:
<code class="javascript">var CommentsWrapper = React.createClass({ render: function () { return <Comments myprop="value" />; } });</code>
This way, you can use CommentsWrapper as the handler for the desired route:
<code class="javascript">var routes = ( <Route path="/" handler={Index}> <Route path="comments" handler={CommentsWrapper}/> <DefaultRoute handler={Dashboard}/> </Route> );</code>
However, this approach can become unwieldy if you need to pass props to multiple handled components. In such cases, a more flexible approach is to use the component property in the route configuration, which allows you to directly pass props to the handled component:
<code class="javascript">var routes = ( <Route path="/" component={Index}/> ); var Index = React.createClass({ render: function () { return ( <div> <header>Some header</header> <RouteHandler myprop="value" /> </div> ); } });</code>
With this approach, you can pass props directly to the Comments component without the need for a wrapper:
<code class="javascript"><Route path="comments" component={Comments}/></code>
The above is the detailed content of How to Pass Props to Handled Components in React Router?. For more information, please follow other related articles on the PHP Chinese website!