React JS:在.map函数中调用时函数未定义
React JS: Function undefined when called in .map function
当我在 React 中使用 map 函数时,我无法使用我已经在构造函数中绑定的函数。在下面的代码中,imageClick
在下面的 map 函数中使用时未定义,尽管我已经绑定了该函数并将 this
作为参数包含在内。知道哪里出了问题吗?
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>
)}
当我在 React 中使用 map 函数时,我无法使用我已经在构造函数中绑定的函数。在下面的代码中,imageClick
在下面的 map 函数中使用时未定义,尽管我已经绑定了该函数并将 this
作为参数包含在内。知道哪里出了问题吗?
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>
)}