当我在 React 中使用 map 函数时,我无法使用已在构造函数中绑定(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/