在react native中检查键盘是否打开?

oalqel3c  于 2023-05-01  发布在  React
关注(0)|答案(1)|浏览(199)

**我只是想改进我的代码。**我想通过React Native检查iOS中Android的键盘是否打开,以便在此基础上进行相应的更改。

下面是我的代码片段,我现在是如何做的。

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();
        };
    }, []);

此代码在键盘打开时给出true,在键盘未打开时给出false。
先谢谢你了
我检查了堆栈溢出,找到了许多解决方案,但是,我所需要的只是一个简单而简短的解决方案。

vecaoik1

vecaoik11#

如果你想要一个更短的版本,你可以创建一个自定义钩子。
下面是一个示例keyboard.js

export const useKeyboardVisible = () => {
    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;
}

然后您可以简单地将其导入到您的组件中

const SampleComponent = () => {
   const isKeyboardVisible = useKeyboardVisible();

   // ...
}
``

相关问题