【问题标题】:How to identify that the keyboard is open or not in react native?如何在本机反应中识别键盘是否打开?
【发布时间】:2022-01-27 14:37:34
【问题描述】:

我有文本输入和一个提交按钮,我在“onendediting”的文本输入上添加了事件,如果我在文本框中输入值并按下提交按钮而不结束编辑,那么事件“onendediting”不会按预期触发。所以我想在键盘打开时跟踪键盘我不允许提交按钮工作。 我该如何处理?我使用了“keyboard.addEventListener”,但它不起作用。

【问题讨论】:

标签: react-native keyboard-events


【解决方案1】:

安卓注意事项:如果您的清单文件包含android:windowSoftInputMode="adjustPan",则该挂钩将无法在安卓上运行。

我为此使用了一个钩子:

import {useEffect, useState} from 'react';
import {Keyboard} from 'react-native';

const useKeyboard = () => {
  const [isKeyboardVisible, setKeyboardVisible] = useState(false);

  useEffect(() => {
    const keyboardDidShowListener = Keyboard.addListener(
      'keyboardDidShow',
      () => {
        setKeyboardVisible(true);
      },
    );

    const keyboardDidHideListener = Keyboard.addListener(
      'keyboardDidHide',
      () => {
        setKeyboardVisible(false);
      },
    );

    return () => {
      keyboardDidHideListener.remove();
      keyboardDidShowListener.remove();
    };
  }, []);

  return isKeyboardVisible;
};

export default useKeyboard;

用法:

import React from 'react';
import {Text} from 'react-native';
import useKeyboard from './useKeyboard';

const App = () => {
  const isKeyboardOpen = useKeyboard();

  return isKeyboardOpen ? <Text>OPEN</Text> : <Text>CLOSE</Text>;
};

【讨论】:

  • 以上示例不适用于我的情况。我的清单文件包含 android:windowSoftInputMode="adjustResize"。
猜你喜欢
  • 2019-05-06
  • 1970-01-01
  • 2020-04-22
  • 2018-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-25
  • 2016-09-30
相关资源
最近更新 更多