我想知道当你传递一个函数时 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(){...}
};