Fez*_*sta 14 javascript destructuring reactjs ecmascript-next
我有:
const section = cloneElement(this.props.children, {
className: this.props.styles.section,
...this.props,
});
Run Code Online (Sandbox Code Playgroud)
在里面this.props,我有一个styles我不想传递给克隆元素的属性.
我能怎么做?
ctr*_*usb 23
您可以使用object 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,
});
Run Code Online (Sandbox Code Playgroud)
我假设您已经基于上面的代码获得了此语法的支持,但请注意,这是一种建议的语法,可通过babel阶段1预设提供给您.如果执行时出现语法错误,可以按如下方式安装预设:
npm install babel-preset-stage-1 --save-dev
Run Code Online (Sandbox Code Playgroud)
然后将其添加到babel配置的预设部分.例如,在.babelrc文件中:
"presets": [ "es2015", "react", "stage-1" ]
Run Code Online (Sandbox Code Playgroud)
根据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,
});
Run Code Online (Sandbox Code Playgroud)
am0*_*0wa 10
您可以使用Object Rest Spread 运算符魔术。
const props = { a: 1, b: 2, c: 3 };
const { a, ...propsNoA } = props;
console.log(propsNoA); // => { b: 2, c: 3 }
Run Code Online (Sandbox Code Playgroud)
所以在你的情况下,它将是:
const { styles, ...propsNoStyles } = this.props;
const section = cloneElement(this.props.children, {
className: this.props.styles.section
...this.propsNoStyles,
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7358 次 |
| 最近记录: |