【发布时间】: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”(…)
在这种情况下如何从循环中调用此函数?
【问题讨论】:
-
设置
this为.map回调 -this.getDefaultLists().map(function(item,index){ ... }, this) -
或者只使用粗箭头
-
谢谢@AlexanderT。但它没有发送数据对象。
-
可能与 [this question][1] [1] 重复:stackoverflow.com/a/40639996/2902660
标签: javascript reactjs