簡體   English   中英

React JS:在.map函數中調用時函數未定義

[英]React JS: Function undefined when called in .map function

當我在React中使用map函數時,我無法使用已經綁定到構造函數中的函數。 在下面的代碼中,盡管我已經綁定了該函數並將this作為參數,但在下面的地圖函數中使用imageClick未定義。 知道有什么問題嗎?

export default class ScrapeInstagram extends React.Component { 

constructor(props) {
  super(props);
  this.imageClick = this.imageClick.bind(this);
}

imageClick() {
  console.log("made it here!")
}

render() {
    return (
    <Container>
        <center>
            <h1> A bunch of photos! </h1>
            <div className="box">
            {this.searchResults.map(function(photo){
                return <div className="dataSetBox" key={photo.toString()}><img id={id} src={photo} onClick={this.imageClick} alt="Image" height="350" width="450" margin="15px" border= "10"/></div>;
            }, this)}
            </div>
        </center>
    </Container>  
    );
}
}

使用ES6 Arrow函數將幫助您向上訪問封閉上下文的this

{this.searchResults.map(photo) =>
    return <div className="dataSetBox" key={photo.toString()}><img id={id} src={photo} onClick={this.imageClick} alt="Image" height="350" width="450" margin="15px" border= "10"/></div>        
)}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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