破坏对象并忽略结果之一 [英] Destructuring object and ignore one of the results

查看:32
本文介绍了破坏对象并忽略结果之一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有:

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

this.props 里面,我有一个 styles 属性,我不想传递给克隆的元素.

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

我该怎么办?

推荐答案

您可以使用对象放置/spread语法:

// 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

然后将其添加到babel配置的预设"部分.例如,在您的.babelrc文件中:

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

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


根据OP对问题的评论进行更新.

好吧,那么您说您已经在此块之前声明了一个 styles 变量吗?我们也可以处理这种情况.您可以重命名已分解的参数来避免这种情况.

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.

例如:

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,
});

这篇关于破坏对象并忽略结果之一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆