What do these three dots in React do?

前端 未结 29 2586
不思量自难忘°
不思量自难忘° 2020-11-21 23:53

What does the ... do in this React (using JSX) code and what is it called?



        
29条回答
  •  旧巷少年郎
    2020-11-22 00:14

    It's just defining props in a different way in JSX for you!

    It's using ... array and object operator in ES6 (object one not fully supported yet), so basically if you already define your props, you can pass it to your element this way.

    So in your case, the code should be something like this:

    function yourA() {
      const props = {name='Alireza', age='35'};
      
    }
    

    so the props you defined, now separated and can be reused if necessary.

    It's equal to:

    function yourA() {
      
    }
    

    These are the quotes from React team about spread operator in JSX:

    JSX Spread Attributes If you know all the properties that you want to place on a component ahead of time, it is easy to use JSX:

    var component = ;
    

    Mutating Props is Bad
    If you don't know which properties you want to set, you might be tempted to add them onto the object later:

    var component = ;
    component.props.foo = x; // bad
    component.props.bar = y; // also bad
    

    This is an anti-pattern because it means that we can't help you check the right propTypes until way later. This means that your propTypes errors end up with a cryptic stack trace.

    The props should be considered immutable. Mutating the props object somewhere else could cause unexpected consequences so ideally it would be a frozen object at this point.

    Spread Attributes
    Now you can use a new feature of JSX called spread attributes:

    var props = {};
        props.foo = x;
        props.bar = y;
        var component = ;
    

    The properties of the object that you pass in are copied onto the component's props.

    You can use this multiple times or combine it with other attributes. The specification order is important. Later attributes override previous ones.

    var props = { foo: 'default' };
    var component = ;
    console.log(component.props.foo); // 'override'
    

    What's with the weird ... notation?
    The ... operator (or spread operator) is already supported for arrays in ES6. There is also an ECMAScript proposal for Object Rest and Spread Properties. We're taking advantage of these supported and developing standards in order to provide a cleaner syntax in JSX.

提交回复
热议问题