问题
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