1

In the render method of CopyButton component, we have the line:

const { classes, theme, hidden, ...other } = this.props;

What does it mean? = is an assigngment operator, and an object(denoted by the {}) is its left value? How can an object be the left value of an assignment?

Besides, what does ...other mean, I know that ... is a expand operator, but what does other stand for?


Below is the whole piece of codes:

export class CopyButton extends Component {
  static propTypes = {
    /**
     * @ignore
     */
    classes: PropTypes.object,
    /**
     * @ignore
     */
    theme: PropTypes.object,

    hidden: PropTypes.bool
  };

  render() {
    //赋值操作的左值是一个对象?
    const { classes, theme, hidden, ...other } = this.props;

    const copyIconStyle =
      theme.direction === 'ltr' ? null : { transform: 'scaleX(-1)' };

    return (
      <Scannable disabled={hidden}>
        <IconButton aria-label="Copy" className={classes.button} {...other}>
          <FileCopy className={classes.icon} style={copyIconStyle} />
        </IconButton>
      </Scannable>
    );
  }
}
ZhaoGang
  • 4,491
  • 1
  • 27
  • 39
  • 1
    It's called destructuring, and it can be done with arrays and objects. In this case it's with the props object, here's some documentation about object destructuring: https://javascript.info/destructuring-assignment#object-destructuring – Jayce444 May 11 '21 at 02:57
  • 1
    It's object destructuring assignment ... more info here [MDN reference](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) – KcH May 11 '21 at 02:57
  • 1
    Does this answer your question? [What does the '...rest' stand for, in this spread operator example](https://stackoverflow.com/questions/47689680/what-does-the-rest-stand-for-in-this-spread-operator-example) – Sebastian Simon May 11 '21 at 14:23

1 Answers1

1

This is object destructuring assignment combined with the Spread syntax.

const { classes, theme, hidden, ...other } = this.props;

The props object may have properties that are then destructured and assigned to local variables. In this case, classes, theme, hidden, and the rest of the properties (via the spread syntax) are assigned to an object named other.

const props = {
  classes: 'this is a value',
  theme: 'foo',
  hidden: false,
  otherProp1: 'other 1',
  otherProp2: {
    nestedProp: 'nested value',
  },
};

const { classes, theme, hidden, ...other } = props;

console.log(classes);
console.log(theme);
console.log(hidden);
console.log(other);
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • After the destruction, `this.props` still holds these values(chasses,thems,hidden,...), right? – ZhaoGang May 11 '21 at 03:07
  • 1
    @ZhaoGang ***Destructure***, not destruction. And correct, destructuring leaves the original object/array intact. Also, in React state and props are treated as immutable. – Drew Reese May 11 '21 at 03:09