小编典典

销毁对象并忽略结果之一

reactjs

我有:

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

在内部this.props,我有一个styles我不想传递给克隆元素的属性。

我能怎么做?


阅读 302

收藏
2020-07-22

共1个答案

小编典典

您可以使用对象rest / 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,
});

我假设您已经基于上面的代码获得了此语法的支持,但是请注意,这是一个建议的语法,可通过babel stage
1预设
提供给您。如果在执行时遇到语法错误,则可以如下安装预设:

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

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

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

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

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

例如:

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