react-native keyboardDidShow / keyboardDidHide键盘事件未触发

时间:2019-10-25 07:34:05

标签: reactjs react-native

我正试图通过使用keyboardDidShow/keyboardDidHide事件来利用android上的键盘事件,但是没有一个被触发。我没有正确订阅吗?

"react": "16.9.0",
"react-native": "0.61.2",

android:windowSoftInputMode="adjustResize"

https://facebook.github.io/react-native/docs/keyboard

class HomeScreen extends React.Component {
  state = {
    keyboard: false,
  };

  componentDidMount() {
    this.keyboardDidShowListener = Keyboard.addListener(
      'keyboardDidShow',
      this.handleKeyboardState(true),
    );
    this.keyboardDidHideListener = Keyboard.addListener(
      'keyboardDidHide',
      this.handleKeyboardState(false),
    );
  }

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

  handleKeyboardState(state) {
    console.log('WILL SET KEYBOARD STATE TO', state);
    this.setState({keyboard: state});
  } 

...
}

我的意思是它们确实会触发,但是恰好是在安装组件并执行功能时

 BUNDLE  [android, dev] ./index.js ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ 100.0% (1/1), done.

 LOG  Running "Test app" with {"rootTag":21}
 LOG  false
 LOG  WILL SET KEYBOARD STATE TO true
 LOG  WILL SET KEYBOARD STATE TO false

1 个答案:

答案 0 :(得分:0)

我相信问题是您没有为侦听器使用正确的回调签名。您可以尝试以下方法吗?


  componentDidMount() {
    this.keyboardDidShowListener = Keyboard.addListener(
      'keyboardDidShow',
      () => this.handleKeyboardState(true),
    );
    this.keyboardDidHideListener = Keyboard.addListener(
      'keyboardDidHide',
      () => this.handleKeyboardState(false),
    );
  }