[英]React, “this”, cloneElement and es6
我想知道当你传递一个函数时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(){...}
};
为ES6类删除了React.createClass
确实功能的自动 React.createClass
(另请参阅本文 )。 所以你现在必须手动完成:
…
content: function() {
return React.Children.map(this.props.children, function(child) {
return React.cloneElement(child, {
passThisFunc: this.passThisFunc.bind(this)
})
}.bind(this));
},
…
但你不会在ES6中真正做到这一点。 相反,你首先使用一个箭头函数,它具有词法this
绑定:
class Parent extends React.Component {
constructor() {
super();
this.passthisfunc = (component) => {
// returns the parent
console.log(this);
// Returns the component so I can do component.props.name
console.log(component);
};
}
content() {
return React.Children.map(this.props.children, child =>
React.cloneElement(child, {
passThisFunc: this.passThisFunc
});
);
}
…
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.