【问题标题】:onClick event can't find function in react mapped objectonClick 事件在反应映射对象中找不到函数
【发布时间】:2017-03-31 17:01:28
【问题描述】:

使用 map() 循环对象时,React 找不到自己的 classes 属性!

这里是组件的类,

import React, { Component } from 'react';
import './videolists.css';

export default class VideoLists extends Component {

  constructor() {
    super();
  }

  getDefaultLists() {
    return [
      {
        title: 'Iridescent (Official Video) - Linkin Park',
        url: 'https://www.youtube.com/watch?v=xLYiIBCN9ec',
        id: 'xLYiIBCN9ec' 
      },
      {
        title: 'Ed Sheeran - I\'m A Mess (x Acoustic Sessions)',
        url: 'https://www.youtube.com/watch?v=-t2CR9qZRj0',
        id: '-t2CR9qZRj0' 
      },
      {
        title: 'Ed Sheeran - Lego House [Official Video]',
        url: 'https://www.youtube.com/watch?v=c4BLVznuWnU',
        id: 'c4BLVznuWnU' 
      }
    ]
  }

  itemSelected(itemObject) {
    console.log(itemObject);
  }

  render() {
    return (
      <div>
        <div className='panel panel-default'>
          <div className='panel-heading'>

            <ul className='list-group'>
              {this.getDefaultLists().map(function(item, index){
                return <li 
                          key = { index } 
                          className='list-group-item'
                          onClick={ this.itemSelected.bind(this) }>
                          { item.title } <br/>
                          <small className='listurl'>{ item.url }</small>
                      </li>; 
              })}
            </ul>

          </div>
        </div>
      </div>
    );
  }

}

当用户点击一个项目时,它应该调用名为 itemSelected 的函数并将当前的this 元素与此绑定。

但是当应用程序通过时出现错误。

这是错误信息:

未捕获的类型错误:无法读取未定义的属性“itemSelected”(…)

在这种情况下如何从循环中调用此函数?

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

由于您的地图功能,您正在失去 this 上下文。您不仅需要绑定它,还需要发送数据对象,尽管您需要实际告诉它这样做。像这样。

<ul className='list-group'>
    {this.getDefaultLists().map( (item, index) => {
        return (
            <li key ={index} className='list-group-item' onClick={() => this.itemSelected(item)}>
                { item.title }
                <br/>
                <small className='listurl'>{ item.url }</small>
            </li>
         ); 
    })}
</ul>

您可以尝试隐藏您的上下文,这不是必需的,但值得一试。

const self = this;
...
<ul className='list-group'>
    {self.getDefaultLists().map( (item, index) => {
        return (
            <li key ={index} className='list-group-item' onClick={() => self.itemSelected(item)}>
                { item.title }
                <br/>
                <small className='listurl'>{ item.url }</small>
            </li>
         ); 
    })}
</ul>

【讨论】:

  • 谢谢,但是当我点击同样的错误时:VideoLists.js:100 Uncaught TypeError: Cannot read property 'itemSelected' of undefined(…)
  • 你是如何构建这个的?胖箭头函数绑定你的 this 上下文。所以你不需要隐藏你的这个
猜你喜欢
  • 2013-02-28
  • 2020-07-29
  • 2020-03-25
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 2021-06-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多