react 方法未定义_React - 将组件绑定功能时未定义(React - this is undefined when binding function to component)...

本文探讨了在React应用中如何正确地处理图片加载失败的情况,并实现特定的错误回调函数。作者通过使用Semantic UI React组件库中的元素演示了这一过程,并讨论了在类组件中绑定方法以确保`this`关键字正确引用的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I have this code. I imported some components from Semantic UI.

import React from 'react'

import { Card, Image, Grid } from 'semantic-ui-react'

I am trying to call function when error (404) appears when loading image.

export default class HotelCards extends React.Component {

// constructor

constructor(props){

super(props)

this.handleError = this.handleError.bind(this);

}

// state

state = {}

This is the function I'd like to call: (not that if I log this inside render function I get instance of current class)

handleError() {

console.log(this);

}

render() {

if (!this.props.hotels) return null;

return (

{

this.props.hotels.map(function(e, i) {

return (

From this element:

)

})

}

);

}//render

}//class

However I get error that this is undefined.

TypeError: this is undefined

Stack trace:

render/

...

In vanilla JavaScript my approach for this would be

How do I bind this function to component properly?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值