繁体   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