Javascript 分解对象并忽略其中一个结果
我有: 在Javascript 分解对象并忽略其中一个结果,javascript,reactjs,destructuring,ecmascript-next,Javascript,Reactjs,Destructuring,Ecmascript Next,我有: 在this.props中,我有一个styles属性,我不想传递给克隆的元素 我该怎么办?您可以使用: 我假设您已经获得了基于上述代码的此语法的支持,但请注意,这是一种建议的语法,可通过提供给您。如果执行时出现语法错误,可以按如下方式安装预设: // We destructure our "this.props" creating a 'styles' variable and // using the object rest syntax we put the rest of the p
this.props
中,我有一个styles
属性,我不想传递给克隆的元素
我该怎么办?您可以使用:
我假设您已经获得了基于上述代码的此语法的支持,但请注意,这是一种建议的语法,可通过提供给您。如果执行时出现语法错误,可以按如下方式安装预设:
// 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配置的预设部分。例如,在.babelrc文件中:
npm install babel-preset-stage-1 --save-dev
根据OP对问题的评论进行更新 好的,你说在这个块之前已经声明了一个
styles
变量?我们也可以处理这个案子。可以重命名已分解的参数以避免这种情况
例如:
"presets": [ "es2015", "react", "stage-1" ]
我喜欢ctrlplusb的答案,但如果您不想添加新的巴别塔预设,这里有一个替代方法:
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,
});
或者你可以这样做
const section = cloneElement(this.props.children, {
className: this.props.styles.section,
...Object.assign({}, this.props, {
styles: undefined
})
});
你可以用魔法
因此,在您的情况下,它将是:
const props = { a: 1, b: 2, c: 3 };
const { a, ...propsNoA } = props;
console.log(propsNoA); // => { b: 2, c: 3 }
我认为这不适用于react预设。如果您解释了如何配置Babel来利用它,这将是非常有用的。这是一个非常有创意的答案,我不知道这在spread运算符中是可能的。现在,我正在定义
样式:null
之后…this.props
,它可以工作,但这不是很好。你试过我的答案了吗?是的,很抱歉它对我不起作用,因为我之前已经定义了style
。好的,那么你已经在上面声明了style
变量及其冲突。我已经根据这些信息更新了我的答案。那么你有一个未定义的属性,它不会对你的应用程序产生影响。如果您试图访问未传递到组件的属性
,那么该值无论如何都将是未定义的
。这几乎是等价的,只要你不依赖于提供给你道具的特定钥匙的存在@ctrlplusb@am0wa这一切都是好的,但后来的es林特或其他人哭了,因为我只是想忽略第一个。。。还没有找到一个好办法让它消失,并使短绒happy@RangerReturn您可以使用//tslint:disable next line
var newProp = (this.props = {p1, p2,...list out all props except styles});
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,
});