解构对象并忽略其中一个结果

新手上路,请多包涵

我有:

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

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

我能怎么做?

原文由 Fez Vrasta 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 365
2 个回答

您可以使用 对象 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 preset 提供给您。如果您在执行时遇到语法错误,您可以按如下方式安装预设:

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

原文由 ctrlplusb 发布,翻译遵循 CC BY-SA 3.0 许可协议

您可以使用 Object Rest Spread 运算符 魔法。

 const props = { a: 1, b: 2, c: 3 };
const { a, ...propsNoA } = props;
console.log(propsNoA); // => { b: 2, c: 3 }

所以在你的情况下它将是:

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

原文由 am0wa 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题