解构对象并忽略结果之一

IT技术 javascript reactjs destructuring ecmascript-next
2021-04-13 04:31:36

我有:

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

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

我能怎么做?

4个回答

您可以使用对象休息/传播语法

// 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,
});
这是一个非常有创意的答案,我不知道传播运算符可以做到这一点
2021-05-25 04:31:36
我不认为这与反应预设开箱即用。如果你解释了如何配置 Babel 以利用它,那将会很有用。
2021-06-21 04:31:36

您可以使用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 这一切都好,但随后 es-lint 或其他人哭了,因为我只想忽略第一个……还没有找到让它消失并使 linter 快乐的好方法
2021-05-30 04:31:36
这似乎与@ctrlplusb 提供的答案相同
2021-06-07 04:31:36
@RangerReturn 你可以使用 // tslint:disable-next-line
2021-06-20 04:31:36

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

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

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

const section = cloneElement(this.props.children, {
    className: this.props.styles.section,
    ...Object.assign({}, this.props, {
        styles: undefined
    })
});
那么你有一个未定义的属性
2021-06-02 04:31:36
这应该不会对您的应用程序产生影响。如果您尝试访问prop未传递给您的组件的 a,则该值将是undefined无论如何。这几乎是等价的,前提是您不依赖提供给道具的特定密钥的存在。
2021-06-18 04:31:36