React路由技术疑问:带参数URL时子组件为何置于属性中?<Person />为何需放在Route的children属性而非标签间且用{}包裹?
Hey there! Let's unpack your React questions one by one—these are super common confusions when getting started with routing and JSX, so great call asking about them.
1. Why put child components in props when URLs have parameters?
When your URL includes dynamic parameters (like /person/:id), placing the child component in a Route prop (usually render or children) lets you directly access routing-related data (like match.params) and pass it to your component.
For example, if you need to pass the id parameter to your <Person /> component, you can use the render prop to get the match object and pass the parameter as a prop:
<Route path="/person/:id" render={({ match }) => <Person id={match.params.id} />} />
If you just put <Person /> inside the <Route></Route> tags without using this prop pattern, your <Person /> component won't automatically receive the route parameters (unless you use hooks like useParams() inside it, but this isn't an option for class components). Using the prop approach gives you explicit control over passing data from the route to your component.
2. Why put <Person /> in the Route's children prop instead of between <Route></Route> tags?
First off—these two approaches are sometimes equivalent! Writing <Route><Person /></Route> is actually shorthand for <Route children={<Person />} />. The key difference comes when you need dynamic rendering logic:
The children prop can accept a function that receives routing props (match, location, history), which lets you conditionally render content even if the route doesn't match. For example:
<Route path="/person/:id" children={({ match }) => { // Render Person if the path matches, else render a fallback return match ? <Person id={match.params.id} /> : <div>Oops, that person doesn't exist!</div>; }} />
You can't do this with the tag-between approach, since that only accepts static JSX. Some developers also prefer the prop syntax for readability, especially when the Route has multiple attributes (like exact or strict)—keeping everything on one line makes the component's purpose clearer at a glance.
3. Why is <Person /> wrapped in {}?
Great catch—you're right that {} in JSX is for wrapping JavaScript expressions, and <Person /> absolutely counts as one!
Under the hood, Babel compiles JSX like <Person /> into plain JavaScript: React.createElement(Person, null). This is a function call that returns a React element, which is a valid JavaScript expression.
When you use an expression as a prop value (like children={<Person />}), you need the {} to tell React "this isn't a string—it's JavaScript code to evaluate". If you omitted the braces and wrote children="<Person />", React would render the literal string <Person /> instead of your component.
内容的提问来源于stack exchange,提问作者Bear Bile Farming is Torture

