[英]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.