gpt4 book ai didi

javascript - 将 onClick 处理程序附加到填充的列表项 reactjs

转载 作者:行者123 更新时间:2023-11-30 11:48:11 25 4
gpt4 key购买 nike

我有一个函数,我想在单击按钮时触发,该按钮包含在一个列表项中,该列表项根据从父组件传递的数组中的值进行填充,但它不起作用并返回错误说这个函数是未定义的,我怎样才能让它工作?

import React from 'react';

export default class Card extends React.Component {

constructor(){
super()
this.state = {
index: null
};
}

handleClick(x){
this.setState({
index: x
})

}

render(){
/**
* Populates list items according to data passed
* on to resultsArray.
*/
var items = this.props.resultsArray;
var itemslist = items.map(function(item, index){
return(
<li key={ index } class="card" >
<div class="card-header">
<span class="hour-price"><span>{ item.hourPrice } &euro; /hour</span></span>
<img src={ item.image } class="card-img" />
<a href="javascript:" onClick={this.handleClick.bind(this, {index})} class="book-button">Book</a>
</div>
<div>
<div class="card-info">
<p class="workplace-name">{ item.name }</p>
<span class="score">{ item.score } &#9733;</span>
<p class="location">{ item.location }</p>
</div>
<div class="card-footer">
<p class="price">{ item.price } &euro; / Day</p>
</div>
</div>
</li>
);})
return(
<div class="results-container">
<ul class="card-list center">
{ itemslist }
</ul>
</div>
);

}
}

最佳答案

您应该将您的render 更改为以下代码。使用 that 而不是 this

var items = this.props.resultsArray;
var that = this;
var itemslist = items.map(function(item, index){
return(
<li key={ index } className="card" >
<div className="card-header">
<span className="hour-price"><span>{ item.hourPrice } &euro; /hour</span></span>
<img src={ item.image } className="card-img" />
<a href="javascript:" onClick={that.handleClick.bind(that, index)} className="book-button">Book</a>
</div>
......

关于javascript - 将 onClick 处理程序附加到填充的列表项 reactjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40231850/

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