gpt4 book ai didi

javascript - onClick 事件在 react 映射对象中找不到函数

转载 作者:行者123 更新时间:2023-12-02 13:56:42 25 4
gpt4 key购买 nike

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

这是组件的类,

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 元素与 this 绑定(bind)。

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

这是错误消息:

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

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

最佳答案

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

<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 上下文,这不是必需的,但值得一试。

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 - onClick 事件在 react 映射对象中找不到函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40650055/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com