反应传递道具的简写

and*_*ree 14 reactjs

我厌倦了一直这样做:

<Elem x={x} y={y} z={z} />
<Elem x={this.props.x} y={this.props.y} z={this.props.z} />
Run Code Online (Sandbox Code Playgroud)

有没有办法可以让这样的东西起作用?

<Elem x, y, z />
Run Code Online (Sandbox Code Playgroud)

要么

<Elem {x, y, z} />
Run Code Online (Sandbox Code Playgroud)

小智 33

如果您的变量包含在对象中,例如this.props,您传播对象:

<Elem {...this.props} />
Run Code Online (Sandbox Code Playgroud)

否则,您传播包含所需变量的新对象:

<Elem {...{ x, y, z }} />
Run Code Online (Sandbox Code Playgroud)

  • 这被计算为对象分配。如果你只提供一个对象并立即传播它时,它只是创建一个新对象会更好 (2认同)

Ali*_*ati 7

应该注意的是,这仅适用于对象。例如:

this.props = {
  x: 'foo', 
  y: 'bar',
  z: 'baz',
}

const {
  x,
  ...allOtherProps
} = this.props

<Elem { ...allOtherProps } /> // works (allOtherProps is an object)
<Elem { ...x } /> // does not work (x is not an object)
<Elem x={ x } /> // works
Run Code Online (Sandbox Code Playgroud)

  • `&lt;Elem {...{x, y, z}}/&gt;` (14认同)

Kan*_*naj 6

如注释中所指定的,您应该使用扩展运算符作为向组件发送多个参数的简写.

<Elem {...this.props} />

如果Elem组件是无状态组件,您应该能够像在组件上传递的任何参数一样访问props.this.props在这种情况下,您可能不需要使用关键字.