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

萝らか妹 提交于 2019-12-05 07:56:35
chantastic

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/

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!