reactjs - 无法读取渲染循环中未定义的属性

标签 reactjs

我是 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/

相关文章:

reactjs - 通过 API 调用设置表单的初始值

javascript - react .js : Show '...' after value in input element onBlur if value overflows input element

node.js - 安装: react-native init fails - Apparent network issue

reactjs - React + ASPNET Core + 预渲染 : An attempt was made to access a socket in a way forbidden by its access permissions

javascript - 如何使用 useMemo 钩子(Hook)来内存 child

reactjs - material-ui 如何覆盖嵌套样式

reactjs - 部署到 GitHub 的 React 应用程序给我一个缩小的错误 #152

javascript - --如何让这个 React/Redux 代码变得 DRY

reactjs - 这两种 Material-UI 导入方式有区别吗?

javascript - 我如何对对象进行冒泡排序?