React路由时向组件传递Props的实现方法及代码解析
Hey there! Let's walk through the most common, practical ways to pass props to your React components while using React Router, using your existing route setup as a reference.
1. Use the render Prop Instead of component
This is the go-to approach when you need to pass custom props alongside React Router's default props (like match, location, history). Instead of passing your component directly to the component prop, use render to return an instance of your component with all the props you need.
Here's how to tweak your existing /create route:
class App extends React.Component { render() { // Example custom props you might want to pass const currentUser = { id: 42, name: "Alex Morgan" }; const appContext = { appName: "Document Manager", theme: "light" }; return ( <Router> <div> <Switch> <Route exact path='/' component={Home} /> <Route path='/home' component={Home} /> {/* Updated route using the render prop */} <Route path='/create' render={(routerProps) => ( <CreateRequest {...routerProps} // Passes default router props (match, location, history) user={currentUser} // Your custom user prop context={appContext} // Another custom prop for app-wide data /> )} /> {/* Other routes... */} </Switch> </div> </Router> ); } }
Why {...routerProps}? This spreads all the router-specific props into your component, so you can still use things like this.props.history.push() to navigate inside CreateRequest.
2. Use the children Prop
If you want your component to render even when the route doesn't match (great for persistent UI elements like highlighted navigation links), use the children prop. For page-level components, this is less common, but it's a handy trick to know:
<Route path='/create'> <CreateRequest user={currentUser} context={appContext} /> </Route>
If you need access to router state here, your class component can still use this.props.match to check if the route is active, or functional components can use the useRouteMatch hook.
3. Pass Dynamic Data via Route Parameters
If you need to pass dynamic values (like a document ID or user slug) through the URL, define route parameters and access them in your component.
First, update your route to include a parameter:
<Route path='/search/:documentId' component={SearchDocument} />
Then, in your SearchDocument class component, grab the parameter from this.props.match.params:
class SearchDocument extends React.Component { render() { const { documentId } = this.props.match.params; // Use documentId to fetch data or pass to child components return <div>Looking up document with ID: {documentId}</div>; } }
Bonus: For Functional Components
If you later refactor to functional components, you can use React Router hooks like useParams, useLocation, and useHistory to access router data. You'll still pass custom props the same way with render or children—no extra hoops needed.
内容的提问来源于stack exchange,提问作者Yaswanth

