简体   繁体   中英

How to execute bound function outside of event handler in React?

I'm probably asking the wrong question, but I'd like to be able to execute a parent function when called from a child function, not an event.

I have more or the less the following setup: Declaring the _foo method in the parent and passing it on down to ChildTwo, where executing it via an onClick event handler works as expected. However, I ran into a situation where I need to call the _foo method manually from inside another method (I've simplified it here, but it will be called conditionally).

My question is what do I need to do to call the _foo method from _bar() ?

Thanks in advance!

 export defaultclass Parent extends Component { constructor() { super(); } _foo() { alert('alert!'); } render() { <ChildOne _foo={this._foo.bind(this)} /> } } const ChildOne = (props) => { const { _foo } = props; return ( <ChildTwo _foo={_foo} /> ); } export default class ChildTwo extends Component { constructor(props) { super(props); this._foo = this.props._foo.bind(this); } _bar() { //this._foo.call(); //this._foo(); //what do I do here? } render() { return ( <div> <button onClick={this._foo}> Works! </button> <button onClick={this._bar}>Doesnt Work!</button> </div> ); } }; 

If you really want to do this, then I would solve it by passing the child component as an argument to the method that is still bound to the original parent.

For example:

export defaultclass Parent extends Component {
  constructor() {
    super();
    this._foo = this._foo.bind(this)
  }

  _foo(childComponent) {
    alert({ parent: this, child: childComponent });
  }

  render() { <ChildOne _foo={this._foo} /> }
}

const ChildOne = (props) => {
  const { _foo } = props;
  return ( <ChildTwo _foo={_foo} /> );
}

export default class ChildTwo extends Component {
  constructor(props) {
    super(props);
    this._bar = this._bar.bind(this);
  }

  _bar() {
    const { _foo } = this.props;

    // Passing a reference to self as argument
    _foo(this);
  }

  render() {
      return (
        <div>
          <button onClick={this._bar}>Should Work Now!</button>
        </div>
      );
  }
};

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