[英]Call parent class method from child in ReactJS
我在ReactJS中遇到问题,我想从Child类中调用this.props.onAction()方法,但出现错误:
未捕获的TypeError:this.props.onShotImageClick不是函数
我想在Parent类中动态生成按钮时调用此方法。
var btns = ['aaa', 'bbb', 'ccc']
var Child = React.createClass({
render: function () {
return <button onClick={this.handleClick} type="button"> {this.props.text} </button>;
},
handleClick: function () {
this.props.onAction("super text");
},
});
var Parent = React.createClass({
render: function () {
var buttons = btns.map(function(btn){
return <Child onAction={this.superAction} text={btn} />;
});
return <p>{buttons}</p>;
},
superAction: function (text) {
alert('The Child button say: ' + text);
}
});
React.renderComponent(<Parent />, document.body);
如果我直接在“返回”中调用它,它将起作用。.http://jsfiddle.net/f2ty4jkm/
谢谢。
this
设置为.map
回调,因为在您的情况下, this
是指window
而不是Parent
对象
var buttons = btns.map(function(btn) {
return <Child onAction={this.superAction} text={btn} />;
}.bind(this));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.