简体   繁体   中英

Calling a function inside react-native keyboardDidHide

I am building an app using create-react-native-app and Expo and I would like to call a search function when the on-screen keyboard closes.

class SearchPage extends Component {
  state = {
    modalVisible: false
  };
  componentDidMount() {
    this.keyboardDidHideListener = Keyboard.addListener(
      'keyboardDidHide',
      this._keyboardDidHide
    );
  }

  componentWillUnmount() {
    this.keyboardDidHideListener.remove();
  }

  _keyboardDidHide() {
    this.onSearchButtonPress();
  }
  onSearchButtonPress() {
    this.props.searchCatalog(
      this.props.search,
      this.props.begins,
      this.props.makes
    );
  }
...
}

I have tried calling this.props.searchCatalog(...) directly inside of _keyboardDidHide() but every time I get the same sort of error:

"this.onSearchButtonPress is not a function. (In `this.onSearchButtonPress()', 'this.onSearchButtonPress' is undefined)

Ultimately, all I want to do is call this.props.searchCatalog(...) when the on-screen keyboard closes.

You lost 'this' context. You can fix that using arrow functions:

this.keyboardDidHideListener = Keyboard.addListener(
  'keyboardDidHide',
  () => this.onSearchButtonPress()
);

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