简体   繁体   中英

How do I bind to a function that has been passed in to a child component via a prop so that I can call it in a function in the child component

In the code below, can someone advise on how access the function stored in the closeModal prop that is passed in to the child QRScan component?

I've tried this.props.closeModal.bind(this) in the constructor of QRScan but when I call this.props.closeModal() in the _onBarCodeRead function I get an undefined is not an object (evaluating 'this.props.closedModal') error.

The props are definitely getting passed in to the constructor, I just can't seem to bind the function correctly. Any help much appreciated!

class Test extends React.Component {

constructor(props) {
   super(props);
 }

_test(){
  console.log("test worked")
}

render() {
  return (
    <View>
      <QRScan closeModal={this._test}/>
    </View>
  }
}

Child class:

class QRScan extends React.Component {

constructor(props)
{
 super(props)
 console.log(this.props)
 this.props.closeModal.bind(this);
}

render() {
   return (
    <BarcodeScanner
      onBarCodeRead={this._onBarCodeRead}
      width={windowWidth}
      height={windowWidth * cameraAspectRatio}
      style={styles.camera}>
      <View style={styles.rectangleContainer}>
        <View style={styles.rectangle} />
      </View>
    </BarcodeScanner>
  );
 }
 _onBarCodeRead(e) {
   console.log(e);
   Vibration.vibrate();
   this.props.closeModal();
  }
}

Binding a function does not modify the function in-place. Instead, it returns the resultant function, which you can assign to a variable.

So in theory, you could do this.props.closeModal = this.props.closeModal.bind(this); but that will not work for react. So instead I would recommend creating a method on the class, bind it, and access the props from there. For example:

class QRScan extends React.Component {

  constructor(props)
  {
    super(props)
    this.closeModal = this.closeModal.bind(this)
  }
  closeModal() {
    this.props.closeModal.call(this);
  }
}

Of course, a generally recommended way of doing things would advise keeping this within the class, rather than passing it to your props methods.

To get your code to work, I'd imagine you have to do the same binding with your this._onBarCodeRead method.

The problem is actually the this._onBarCodeRead is not bound correctly.

In the child component's constructor you need to add following this._onBarCodeRead = this._onBarCodeRead.bind(this);

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