[英]React - this is undefined when binding function to component
我有这个代码。 我从语义UI导入了一些组件。
import React from 'react'
import { Card, Image, Grid } from 'semantic-ui-react'
我正在尝试在加载图像时出现错误(404)时调用函数。
export default class HotelCards extends React.Component {
// constructor
constructor(props){
super(props)
this.handleError = this.handleError.bind(this);
}
// state
state = {}
这是我要调用的函数:(不是,如果我在render函数中登录this
函数,则会得到当前类的实例)
handleError() {
console.log(this);
}
render() {
if (!this.props.hotels) return null;
return (
<Grid doubling stackable columns="4" className="cards-container">
{
this.props.hotels.map(function(e, i) {
return (
<Grid.Column key={i} className="card-column">
<Card>
从这个元素:
<Image src={e.hotel.image} onError={this.handleError} />
</Card>
</Grid.Column>
)
})
}
</Grid>
);
}//render
}//class
但是我得到的错误是this
是undefined
。
TypeError: this is undefined
Stack trace:
render/<@http://localhost:1337/app/bundle.js:63883:92
...
在香草JavaScript中,我的处理方法是
<img src="image.png" onError="this.onerror=null;this.src='/placeholder.jpg';" />
如何将该功能正确绑定到组件?
典型的方法是使用所谓的“后期绑定”,即
constructor() {
// ...
this.handleError = this.handleError.bind(this);
}
handleError() {
console.log('THIS', this);
}
您的代码不起作用的原因是,您的粗箭头绑定到了定义类的上下文中。
或者,您也可以按照另一个答案中的建议在渲染级别进行绑定,因此:
<Image src={e.hotel.image} onError={this.handleError.bind(this)} />
但是,该解决方案的问题在于,它会在每次调用render
方法时产生一个新的处理函数,如果使用某种属性相等测试优化,则可能(但不必)对渲染性能产生负面影响。技术。
ES6不支持将粗箭头功能用作类中的方法,因此您首先必须将handError定义为如下方法:
handleError() {
console.log('test');
}
你应该能够绑定到它,所以如果需要它可以使用这样的 :
<Image src={e.hotel.image} onError={this.handleError.bind(this} />
要使渲染函数中的绑定无效(在某些情况下可以提高性能),可以在构造函数中进行绑定:
this.handleError = this.handleError.bind(this);
玉家伙,我发现原因所在this
是undefined
。
这是因为这些东西发生内部.map
方法,所以我不得不绑定this
它是这样的:
this.props.hotels.map(function(e, i) {
...
}, this)
或@apendua评论,通过使用箭头功能, this
就不会丢失:
this.props.hotels.map((e, i) => {
...
})
@kunok:很高兴您找到了答案。 箭头函数(=>)保持此上下文与封闭函数相同。
添加this.state是组件内部的构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.