我想知道当您将 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>
)
}
});
然后在它的 child 中:
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(){...}
};
最佳答案
autobinding React.createClass
确实包含 was removed对于 ES6 类(另见 this article)。所以你现在必须手动完成:
…
content: function() {
return React.Children.map(this.props.children, function(child) {
return React.cloneElement(child, {
passThisFunc: this.passThisFunc.bind(this)
})
}.bind(this));
},
…
但是在 ES6 中你不会真正这样做。相反,您首先会使用箭头函数,它具有词法 this
绑定(bind):
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
});
);
}
…
}
关于javascript - react , "this",cloneElement 和 es6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31841949/