How to override event handler function of child component from parent component in react.js

StackOverflow https://stackoverflow.com/questions/21180550

  •  29-09-2022
  •  | 
  •  

Question

/** @jsx React.DOM */

var Button = React.createClass({
  handleClick: function(){
    console.log(' FROM BUTTON')
  },
  render: function() {
    return <input type='button' onClick={this.handleClick} value={this.props.dname}/>;
  } 
});

var Text = React.createClass({
  render: function() {
    return <input type='text' onClick={this.handleClick} value={this.props.ival}/>;
  } 
});


var search = React.createClass({
  handleClick: function() {
    console.log('searching')
  },
  render: function(){
    return (
      <div>
        <Text/>
        <Button dname={this.props.dname} onClick={this.handleClick} />
      </div>
    );
  }
});

React.renderComponent(<search dname='Look up' fname='Search'/> , document.body);

I have created a button and text component and included them in a search component now i want to override the default handleClick event of button with search component's handler. But this.handleClick is pointing to button component's event handler.. please help.. i need FROM SEARCH on click instead i got FROM BUTTON..

Était-ce utile?

La solution

You are 99% percent there.

React uses a one-way data-flow. So, events on nested components will not propagate to their parents.

You must propagate events manually

Change your <Button>s handleClick function to call the this.props.handleClick function passed in from it's <Search> parent:

var Button = React.createClass({
  handleClick: function () {
    this.props.onClick();
  },

  ...

});

Attached is a fiddle of your original post, with the required change. Instead of logging FROM BUTTON, it will now alert searching.

http://jsfiddle.net/chantastic/VwfTc/1/

Autres conseils

You need to change your Button component to allow such behaviour:

var Button = React.createClass({
  handleClick: function(){
    console.log(' FROM BUTTON')
  },
  render: function() {
    return (
      <input type='button'
        onClick={this.props.onClick || this.handleClick}
        value={this.props.dname} />
    );
  }   
});

note the onClick={this.props.onClick || this.handleClick}.

That way if you pass an onClick prop when instantiating Button it will have a preference over the Button's handleClick method.

Or if you can execute both of them, you can put

class Button extends React.Component {


handleClick = () => {
console.log("from buttom");

if (this.props.hasOwnProperty('onClick')){
   this.props.onClick();
}

};

You would check whether the object has the specified property and run it

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top