javascript - React JS : Function undefined when called in . map 函数

标签 javascript reactjs this array.prototype.map

当我在 React 中使用 ma​​p 函数时,我无法使用已在构造函数中绑定(bind)的函数。在下面的代码中,尽管我已绑定(bind)该函数并包含 this 作为参数,但在下面的 map 函数中使用时 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 箭头函数,这将帮助您向上访问封闭上下文的 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>        
)}

关于javascript - React JS : Function undefined when called in . map 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49159682/

相关文章:

java - 构造函数使用这个和 super Java

javascript - 删除输出中的 %20

javascript - someObject.$() 含义

javascript - Chrome 和 Firefox 的 clientWidth 区别?

javascript - 在命名空间函数中引用所需的对象

c++ - 将 "this"从父类方法转换到子类方法是一个好的做法吗?

javascript - 使用jquery添加html表格行无法设置为标记

javascript - React TypeScript 如何遍历一个对象?

node.js - 我应该从头开始在 React Native 项目上使用 jest 或 jest-cli 吗?

javascript - Url Loader,加载我的背景图片一次,然后在刷新页面后它无法显示