我有:
const section = cloneElement(this.props.children, {
className: this.props.styles.section,
...this.props,
});
在
this.props
内部,我有一个styles
属性,我不想传递给克隆的元素。我能怎么做?
最佳答案
您可以使用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,
});