简体   繁体   中英

How does the {…props} syntax pass its properties down to the subcomponent?

Using React-Router, I learned you can pass route properties down to a component like so:

<Route path="/lyrics/track/:id" render={props => (
    <Component {...props} title={"gah"} content={"blabla"}  />
</Route>

And somehow this appends properties of the props variable here that's a RouteComponentProps to the this.props variable of Component , so now in Component I can do for instance:

<p>{this.props.title}</p>
<p>{this.props.content}</p>
<p>{this.props.match.params.id}</p>

I'm just confused about the {...props} syntax and how this works, as someone relatively new to Javascript. Does that work because both variables have the same name? What makes it so these properties get added unto that particular variable?

The ... is used to spread values in any variable.

when you pass ...props to Component you will get all the properties from the props variable.

read more about Spread syntax

Spreading doesn't have anything to do with the variable name, per se.

In JSX, anything that you declare inside of the tag becomes a property of the props object of the component.

All that you're doing in this case is getting the props from the route and making them available to the component by using the ... spread operator, which would work for any given object.

If you happened to have another object that looked like foobar = { foo: true, bar: false } , you'd also be able to spread that object into the component props.

<Component {...props} {...foobar} title={"gah"} content={"blabla"}  />

This would cause the properties foo and bar to be available inside the component props as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM