<Component {... {myProp:this.props.myProps}} /> vs <Component myProp = {this.props.myProps} />;

Sti*_*ead 1 reactjs

我在一个应用程序中,我刚刚开始,我试图了解与语法有什么区别,有什么方法

<Component {...{myProp : this.props.myProps}} />

VS

<Component myProp={this.props.myProps} />

Hen*_*son 5

你的两种方法之间的区别在于你隐含地传递n个道具的第一个方法.在第二个你明确传递道具.

运算符称为spread,...运算符,在React世界中,它将数组或对象解包为keyworded参数,prop={value}.在仅JavaScript的世界中,它只能解包数组.

这意味着React想要呈现这个:

<Component myProp={this.props.myProps} />
Run Code Online (Sandbox Code Playgroud)

面对时

<Component {...{myProp : this.props.myProps}} />
Run Code Online (Sandbox Code Playgroud)

在您的示例中,您的两种方法在输出方面没有区别,但在面对props结构的更实际示例时差别很大.

要么你明确传递一些道具

this.props = {
    myProp: 1,
    otherProps: 'limelights'
}

<Component myProps={this.props.myProp} myOtherProp={this.props.otherProp} />
Run Code Online (Sandbox Code Playgroud)

或者你Component无论如何都要通过所有这些,并且无论如何都要处理传入的道具.

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