【发布时间】:2015-10-28 18:52:28
【问题描述】:
我想知道当你传递一个函数时 ES6 和 cloneElement 是如何工作的。我需要在父组件的状态中引用状态,但 this 引用子组件而不是父组件。
下面是用常规 JavaScript 编写的代码,使其工作,在第一次用 ES6 编写它并敲击键盘后,我决定看看它是否是 ES6,所以我重构了它,它工作得很好。
我只想用 ES6 编写它,因为其他一切都是这样,但这让我很难过。
这是我在 ES5 中的组件:
var Parent = React.createClass({
content: function() {
return React.Children.map(this.props.children, function(child) {
return React.cloneElement(child, {
passThisFunc: this.passThisFunc
})
}.bind(this));
},
passthisfunc: function(component) {
// returns the components props
console.log(this);
// Returns the component so I can do component.props.name
console.log(component);
},
render: function() {
return (
<div>
{ this.content }
</div>
)
}
});
然后在它的孩子中:
var Child = React.createClass({
componentDidMount: function() {
this.props.passThisFunc(this);
}
render: function().....
});
组件在 ES6 中并没有太大的不同,它确实是在记录 this 时引用的。
任何重构方面的帮助(尤其是父组件)将不胜感激。
编辑 这是我尝试过的 ES6 示例:
class Parent extends React.Component {
content() {
return React.Children.map(this.props.children, function(child) {
return React.cloneElement(child, {
passThisFunc: this.passThisFunc
})
}.bind(this));
}
passthisfunc(component) {
// returns the components props
console.log(this);
// Returns the component so I can do component.props.name
console.log(component);
}
render() {
return (
<div>
{ this.content }
</div>
)
}
};
class Child extends React.Component {
componentDidMount() {
this.props.passThisFunc(this);
}
render(){...}
};
【问题讨论】:
-
你能修复
content中的语法错误吗? -
ES6 并没有改变
this的工作方式。如果不是child.props,您对this的期望值是多少? -
我在
content中的内容与我在当前实现中的内容基本相同,并且工作正常,语法错误是什么?同样关于你的第二个问题,我想做类似的事情:this.setState({ test: 'test' })所以我想我希望它是this以等于它在 ES5 中的父组件。 -
.map(调用错过了它的右括号,并且在您传递给React.createClass({…})的那个对象文字中,第一个属性用;而不是逗号分隔,第二个错过了完全逗号。 -
好电话,谢谢。已更新。
标签: javascript reactjs ecmascript-6