【问题标题】:Destructuring object and ignore one of the results解构对象并忽略其中一个结果
【发布时间】:2016-10-16 18:22:56
【问题描述】:

我有:

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

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

我该怎么办?

【问题讨论】:

  • 现在我只是在 ...this.props 之后定义 styles: null 并且它有效,但它不是超级好。
  • 你试过我的答案了吗?
  • 是的,很抱歉它对我不起作用,因为我之前已经定义了 styles
  • 好的,所以你已经在上面声明了一个styles 变量并且它发生了冲突。我已根据此信息更新了我的答案。

标签: javascript reactjs destructuring ecmascript-next


【解决方案1】:

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

我假设您已经根据上面的代码获得了此语法的支持,但请注意,这是一个建议的语法,可通过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,
});

【讨论】:

  • 我认为这不适用于 react 预设。如果你解释了如何配置 Babel 来使用它,那将会很有用。
  • 这是一个非常有创意的答案,我不知道使用传播运算符可以做到这一点
【解决方案2】:

你可以使用Object Rest Spread operator魔法。

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

【讨论】:

  • 这似乎与@ctrlplusb 提供的答案相同
  • @am0wa 这一切都好,但是 es-lint 或其他人哭了,因为我只是想忽略第一个...还没有找到一个好方法让它消失并让 linter 开心
  • @RangerReturn 你可以使用// tslint:disable-next-line
【解决方案3】:

或者你可以做这样的事情......

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

【讨论】:

    【解决方案4】:

    我喜欢 ctrlplusb 的回答,但如果您不想添加新的 babel 预设,这里有一个替代方案,使用 Object.assign

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

    【讨论】:

    • 那么你有一个未定义的属性
    • 这不应该对您的应用程序产生影响。如果您尝试访问未传递给您的组件的prop,则无论如何该值将是undefined。这几乎是等价的,只要您不依赖提供给道具的特定密钥的存在。
    猜你喜欢
    • 1970-01-01
    • 2017-04-25
    • 2017-08-05
    • 2019-09-25
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 2019-02-09
    • 1970-01-01
    相关资源
    最近更新 更多