Destructuring object and ignore one of the results

时间秒杀一切 提交于 2019-12-04 02:52:42

问题


I have:

const section = cloneElement(this.props.children, {
  className: this.props.styles.section,
  ...this.props,
});

Inside this.props, I have a styles property that I don't want to pass to the cloned element.

How can I do?


回答1:


You can use the object rest/spread syntax:

// We destructure our "this.props" creating a 'styles' variable and
// using the object rest syntax we put the rest of the properties available
// from "this.props" into a variable called 'otherProps' 
const { styles, ...otherProps } = this.props;
const section = cloneElement(this.props.children, {
  className: styles.section,
  // We spread our props, which excludes the 'styles'
  ...otherProps,
});

I assume that you already have support from this syntax based on your code above, but please be aware that this is a proposed syntax which is made available to you via the babel stage 1 preset. If you get syntax errors on execution you can install the preset as follows:

 npm install babel-preset-stage-1 --save-dev

And then add it to the presets section of your babel configuration. For example in your .babelrc file:

 "presets": [ "es2015", "react", "stage-1" ]

Update based on comment on question by OP.

Okay, so you say that you already have a styles variable declared before this block? We can manage this case too. You can rename your destructured arguments to avoid this.

For example:

const styles = { foo: 'bar' };

const { styles: otherStyles, ...otherProps } = this.props;
const section = cloneElement(this.props.children, {
  className: otherStyles.section,
  // We spread our props, which excludes the 'styles'
  ...otherProps,
});



回答2:


I like ctrlplusb's answer, but here is an alternative using Object.assign if you don't want to add a new babel preset:

const section = cloneElement(this.props.children, {
    className: this.props.styles.section,
    ...Object.assign({}, this.props, {
        styles: undefined
    })
});



回答3:


or you can do something like this...

var newProp = (this.props = {p1, p2,...list out all props except styles});


来源:https://stackoverflow.com/questions/37838778/destructuring-object-and-ignore-one-of-the-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!