onClick事件无法在react映射对象中找到函数

onClick event can't find function in react mapped object

本文关键字:对象 函数 映射 react 事件 onClick      更新时间:2023-09-26

在使用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元素与此绑定。

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

错误信息如下:

Uncaught TypeError: Cannot read property 'itemSelected' of undefined(…)

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

由于您的映射函数,您将失去此上下文。你不仅需要绑定那个,要发送数据对象你还需要告诉它这样做。这样的。

<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>

你可以试着给你的this context添加阴影,虽然没有必要,但是值得一试。

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>