简体   繁体   中英

Call parent class method from child in ReactJS

i have a problem in ReactJS I want to call this.props.onAction() method from Child class but i have an error:

Uncaught TypeError: this.props.onShotImageClick is not a function

http://jsfiddle.net/01fbL37L/

I want to call this method when buttons are generated dynamically in Parent class.

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);

If i call it directly in "return" it works.. http://jsfiddle.net/f2ty4jkm/

Thanks.

Set this to .map callback, because in your case this refers to window not to your Parent object

 var buttons = btns.map(function(btn) {
     return <Child onAction={this.superAction} text={btn} />;
 }.bind(this));

Example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM