我正在尝试将方法传递给子组件来处理 onclick 事件。我在网上看到了很多例子,但我无法让它工作。当我在父级的渲染函数中并尝试将“this.handleClick”传递给子级时,handleClick 未定义。
看看 ThumbList 的渲染方法:
var Thumb = React.createClass({
handleClick: function() {
console.log(this)
console.log('handleClick of Thumb')
this.props.onClick()
},
render: function() {
return(
<div className="thumb" key={this.props.thumb.url}>
<a href='#' onClick={this.handleClick}>
<img src={'/img/rings/thumbs/'+this.props.thumb.url+'_thumb.jpg'} alt="Image">
</img>
</a>
</div>
);
}
});
var ThumbList = React.createClass({
handleClick: function (id) {
console.log('click of ThumbList');
},
loadFromServer: function() {
$.ajax({
url: 'rings/imgs/5',
dataType: 'json',
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error('rings/imgs/5', status, err.toString());
}.bind(this)
});
},
getInitialState: function(){
return {data: [] };
},
componentDidMount: function(){
this.loadFromServer();
setInterval(this.loadFromServer, 2000);
},
render: function() {
var handlefunc=this.handleClick
var thumbsNodes = this.state.data.map(function(thumb) {
console.log(this.handleClick) // is Undefined!
console.log(handlefunc) // is working
return (
<Thumb thumb={thumb} key={thumb.url} onClick={handlefunc.bind(this,thumb.url)}/>
);
});
return(
<div className="col-md-1 col-md-offset-1" id='thumbs'>
{thumbsNodes}
</div>
);
}
});
知道我可能缺少什么吗?