简体   繁体   中英

attach onClick handler to populated list item reactjs

i have a function that i want to fire when a button is being clicked, this button is included in a list item that gets populated based on values from an array passed from the parent component, but its not working and returning an error saying that the function is undefined, how can i make this work?

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

  }
}

You should change your render to the below codes. Use that instead of 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>
           ......

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM