onClick事件无法在react映射对象中找到函数
onClick event can't find function in react mapped object
在使用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>
相关文章:
- 创建对象函数原型和代码是错误的
- JavaScript模块模式-如何在使用对象/函数之前激发构造函数/init函数
- 如何从onclick字符串中引用javascript对象函数
- 更改对象函数仅用于示例
- javascript和jQuery的嵌套对象函数中的变量范围
- 将对象函数传递给请求动画帧时丢失对象引用
- 对象函数返回函数而不是值
- 使用onclick调用属性对象函数
- javascript拉斐尔对象函数传递
- 如何从onClick事件调用对象函数
- 可以't获取具有“t”的对象变量;这个“;由setTimeout()函数调用的对象函数中的属性
- 对象没有't继承父对象函数
- 调用父对象函数
- "这个“;对象函数内部的引用
- 将变量添加到对象函数调用的末尾
- 传单错误:对象函数没有方法'createIcon'在LayerGroup中创建自定义图标标记时
- TypeError:对象函数Object(){〔本机代码〕}没有方法'方法'
- 挖空 - 单击绑定到对象函数 - 范围问题
- 类型错误: 对象函数...没有方法“打开”
- JavaScript 对象函数