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

时间:2016-10-25 05:14:26

标签: javascript function reactjs frontend

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

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

  }
}

1 个答案:

答案 0 :(得分:3)

您应该将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>
           ......