简体   繁体   English

{…props}语法如何将其属性传递给子组件?

[英]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: 使用React-Router,我了解到您可以将路由属性传递给类似这样的组件:

<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: 并以某种方式将props变量的属性(这是RouteComponentPropsComponentthis.props变量中,因此现在在Component I中可以执行以下操作:

<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. 作为Java的新手,我对{...props}语法及其工作原理感到困惑。 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. 当您将...props传递给Component您将从props变量中获取所有属性。

read more about Spread syntax 阅读更多有关Spread语法的信息

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. 在JSX中,您在标签内部声明的所有内容都将成为组件的props对象的属性。

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. 在这种情况下,您要做的就是从路线中获取道具,并使用... spread运算符将其提供给组件,该运算符适用于任何给定的对象。

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. 如果您碰巧有另一个看起来像foobar = { foo: true, bar: false } ,则还可以将该对象传播到组件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. 这将导致属性foobar在组件props中也可用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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