如何在React Native中检测键盘何时打开或关闭

fjnneemd  于 2023-01-14  发布在  React
关注(0)|答案(8)|浏览(165)

如何检测用户是否在react native中关闭键盘,我想在用户关闭键盘时调用一个函数。
如果你能回答检测键盘是开放的太将不胜感激,谢谢。
我在看最新的react native version 0.56

u0sqgete

u0sqgete1#

谢谢你们的回答。如果有人感兴趣,这里是hooks版本:

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

 useEffect(() => {
    const keyboardDidShowListener = Keyboard.addListener(
      'keyboardDidShow',
      () => {
        setKeyboardVisible(true); // or some other action
      }
    );
    const keyboardDidHideListener = Keyboard.addListener(
      'keyboardDidHide',
      () => {
        setKeyboardVisible(false); // or some other action
      }
    );

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

4sup72z82#

1.你可以使用facebook上的**Keyboard class**。

下面是一个示例代码。

import React, { Component } from 'react';
import { Keyboard, TextInput } from 'react-native';

class Example extends Component {
  componentWillMount () {
    this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow);
    this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide);
  }
    
  componentWillUnmount () {
    this.keyboardDidShowListener.remove();
    this.keyboardDidHideListener.remove();
  }
    
  _keyboardDidShow () {
    alert('Keyboard Shown');
  }
    
  _keyboardDidHide () {
    alert('Keyboard Hidden');
  }
    
  render() {
    return (
      <TextInput
        onSubmitEditing={Keyboard.dismiss}
      />
    );
  }
}

2.您还可以使用其他一些npm依赖项,比如react-native-keyboard-listener

将组件导入到要使用它的文件中:

import KeyboardListener from 'react-native-keyboard-listener';

直接在代码中使用该组件。该组件不会呈现任何内容

<View>
  <KeyboardListener
    onWillShow={() => { this.setState({ keyboardOpen: true }); }}
    onWillHide={() => { this.setState({ keyboardOpen: false }); }}
  />
</View>

要安装此依赖项,请运行以下命令。

npm install --save react-native-keyboard-listener

选择您觉得更方便的选项。

w1e3prcc

w1e3prcc3#

我用钩子把它包起来:

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

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;
};

钩子返回一个布尔标志,可用于有条件地应用逻辑或运行任何其他所需的效果。

8ehkhllq

8ehkhllq4#

@Khemraj的答案的改进版本(对我来说效果很好),将方法绑定到示例,以便能够从侦听器更新组件的状态并重新呈现。

import React, { Component } from 'react';
import { Keyboard, TextInput } from 'react-native';

class Example extends Component {

  state = {
      keyboardState: 'closed'
  }

  componentWillMount () {
    this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow);
    this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide);
  }

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

  _keyboardDidShow = () => {
    this.setState({
        keyboardState: 'opened'
    });
  }

  _keyboardDidHide = () => {
    this.setState({
        keyboardState: 'closed'
    });
  }

  render() {
    return (
      <TextInput
        onSubmitEditing={Keyboard.dismiss}
      />
    );
  }
}
dxxyhpgq

dxxyhpgq5#

我在@react-native-community/hooks中找到了usekunboard钩子
例如

import { useKeyboard } from '@react-native-community/hooks'

const keyboard = useKeyboard()

console.log('keyboard isKeyboardShow: ', keyboard.keyboardShown)
console.log('keyboard keyboardHeight: ', keyboard.keyboardHeight)

来源:https://github.com/react-native-community/hooks/blob/master/src/useKeyboard.ts

falq053o

falq053o6#

MobX版本:

import { observable } from 'mobx'
import { EmitterSubscription, Keyboard } from 'react-native'

class KeyboardStore {
  @observable isKeyboardVisible = false
  keyboardSubs: EmitterSubscription[] = []

  subKeyboard() {
    this.keyboardSubs = [
      Keyboard.addListener('keyboardDidShow', () => this.isKeyboardVisible = true),
      Keyboard.addListener('keyboardDidHide', () => this.isKeyboardVisible = false),
    ]
  }

  unsubKeyboard() {
    this.keyboardSubs.forEach(sub => sub.remove())
    this.keyboardSubs = []
  }
}

以及顶层应用程序组件内部

useEffect(() => {
    store.subKeyboard()
    return () => {
      store.unsubKeyboard()
    }
  }, [])

并使用store.isKeyboardVisible检查应用中的任意位置。

roqulrg3

roqulrg37#

所有功能都已在react-native Keyboard类中提供

import React, { Component } from 'react';
import { Keyboard, TextInput } from 'react-native';

class Example extends Component {

    componentDidMount() {
        this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow);
        this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide);
        this.keyboardWillShowListener = Keyboard.addListener('keyboardWillShow', this._keyboardWillShow);
        this.keyboardWillHideListener = Keyboard.addListener('keyboardWillHide', this._keyboardWillHide);
    }

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

    _keyboardWillShow() {
        console.log('Keyboard Showning')
    }

    _keyboardWillHide() {
        console.log('Keyboard Heding')
    }

    _keyboardDidShow() {
        alert('Keyboard Shown');
    }

    _keyboardDidHide() {
        alert('Keyboard Hidden');
    }

    render() {
        return (
            <TextInput
                onSubmitEditing={Keyboard.dismiss}
            />
        );
    }
}
gpnt7bae

gpnt7bae8#

我用了一个小混音伟大的答案从@halbano这可能是有用的考虑取决于您的情况

export default function useKeyboardOffsetHeight(): number {
  const [keyBoardOffsetHeight, setKeyboardOffsetHeight] = useState(0);

  useEffect(() => {
    const keyboardWillShowListener = Keyboard.addListener(
      "keyboardWillShow",
      (e) => {
        setKeyboardOffsetHeight(e.endCoordinates.height);
      }
    );
    const keyboardWillHideListener = Keyboard.addListener(
      "keyboardWillHide",
      () => {
        setKeyboardOffsetHeight(0);
      }
    );

    return () => {
      keyboardWillHideListener.remove();
      keyboardWillShowListener.remove();
    };
  }, []);

  return keyBoardOffsetHeight;
}

keyBoardOffsetHeightisKeyboardVisible

我用整数keyBoardOffsetHeight代替了布尔值isKeyboardVisible,因为根据键盘大小移动一些其他组件通常很有用,偏移量可以是0(隐藏)或Y〉0像素(显示),然后我可以在样式中使用它,如下所示:

const keyBoardOffsetHeight = useKeyboardOffsetHeight();
...
    <View
      style={{
        bottom: keyBoardOffsetHeight,
      }}
    >

keyboardWillShowkeyboardDidShow
其次,我使用keyboardWillShow事件,以便能够预测键盘的出现并更早地触发UI更改。
一旦键盘出现,就会触发keyboardDidShow事件。
基于同样的理由,我还使用了keyboardWillHide而不是keyboardDidHide

相关问题