React onClick problems

老子叫甜甜 提交于 2019-12-11 03:16:45

问题


I´m new to React and I´m trying to connect an onClick event to an image to see what object that has been pressed but does not get it to work, I´ve tried several answers that I found on this site but none work, might be because of "var createItem"?

/** @jsx React.DOM */

var React = require("react");
var Firebase = require("firebase");


// CHILD
var CardsList = React.createClass({
    render: function() {
       var createItem = function(card, index) {
           return <div id='card' key={ index }><img onClick={ this.props.onClick.bind(null, this)  } src=        { card.url }/></div>;
    };
    return <div id='cards'>{ this.props.cards.map(createItem) }</div>;
    }
});


//PARENT
var DeckCalculator = React.createClass({
    getInitialState: function() {
        this.cards = [];
        this.userCards = [];
    return {cards: [], name:"default", url:"defaultURL"};
},
    handleOnAdd: function(component, event){
        // Add the clicked card to userCards[]
    },
    render: function() {
    return (
      <div>
        <h3>All Cards</h3>
        <CardsList onClick={ this.handleOnAdd } cards={ this.state.cards } />
      </div>
   );
   }
});

This code gives the error: Uncaught TypeError: Cannot read property 'onClick' of undefined


回答1:


Your createItem has the wrong context.

var createItem = function(card, index) {
  return (
    <div id='card' key={index}>
      <img onClick={this.props.onClick.bind(null, this)} src={ card.url } />
    </div
  );
}.bind(this);

Notice the .bind(this) at the end.

For more information on why this is (haha), check out this article https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this



来源:https://stackoverflow.com/questions/27062760/react-onclick-problems

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!