我有:
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对问题的评论进行更新.
好吧,那么你说你已经在这个块之前声明了一个样式变量?我们也可以管理这个案子.您可以重命名您的结构化参数以避免这种情况.
例如:
const styles = { foo: 'bar' }; const { styles: otherStyles,{ className: otherStyles.section,});