我是 React 新手。我试图将点击处理程序关联到 React 循环中渲染的组件,但收到了 prop undefined 错误。我的代码如下:
import React, { Component } from 'react';
import './ImageGallery.css';
class ImageGallery extends Component {
constructor(props) {
super(props);
this.selectImage = this.selectImage.bind(this);
}
selectImage(e){
console.log(e.target);
}
render() {
return (
this.props.images.map(function(e, i){
return <img alt={i} key={i} src={e} className="thumbnail" onClick={this.selectImage}/>
})
)
}
}
export default ImageGallery;
不幸的是,有关列表和键的文档不太支持我的场景,因为它没有涵盖事件:https://reactjs.org/docs/lists-and-keys.htm
错误消息是:无法读取未定义的属性“selectImage”
最佳答案
使用箭头函数将map
回调替换为以下内容
this.props.images.map((e, i) => {
return <img alt={i} key={i} src={e} className="thumbnail" onClick={this.selectImage}/>
})
或者在return
语句之前保存this
const that = this;
return (
this.props.images.map(function(e, i){
return <img alt={i} key={i} src={e} className="thumbnail" onClick={that.selectImage}/>
})
)
这可能对你有用 - 如何 this
在 JavaScript 中工作。
关于reactjs - 无法读取渲染循环中未定义的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49625216/