簡體   English   中英

在ReactJS中從子級調用父類方法

[英]Call parent class method from child in ReactJS

我在ReactJS中遇到問題,我想從Child類中調用this.props.onAction()方法,但出現錯誤:

未捕獲的TypeError:this.props.onShotImageClick不是函數

http://jsfiddle.net/01fbL37L/

我想在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM