簡體   English   中英

React-將函數綁定到組件時未定義

[英]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

但是我得到的錯誤是thisundefined

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);

玉家伙,我發現原因所在thisundefined

這是因為這些東西發生內部.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM