如何在 React Native 中获得“打开前的键盘高度"? [英] How to get 'Keyboard height before it opens' in React Native?

查看:140
本文介绍了如何在 React Native 中获得“打开前的键盘高度"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

环境:

反应原生 0.60.4

React-Native 0.60.4

问题:

我正在开发聊天应用.聊天有表情符号选择器.表情符号选择器必须与键盘具有相同的高度.我需要在键盘打开之前获得它的高度.我尝试使用键盘侦听器,但打开后它们会给出高度.我的最终目标是按照图片做.你是怎么做到的?

I'm developing chat app. The chat has emoji picker. Emoji picker must to has the same height that keyboard. I need to get the height of the keyboard before it opens. I tried to use keyboard listeners, but they give height after opening it. My ultimate goal is to do as in the picture. How do you do that?

示例:

import React, { useState, useEffect, createRef } from "react";
import {
  Keyboard,
  TextInput,
  View,
  EmitterSubscription,
  Button,
  KeyboardAvoidingView,
  StyleSheet
} from "react-native";

const APPROXIMATE_HEIGHT = 360;

const App = () => {
  let inputRef = createRef<TextInput>();

  const [visible, setVisible] = useState(false);
  const [height, setHeight] = useState(APPROXIMATE_HEIGHT);

  useEffect(() => {
    let keyboardDidShowListener: EmitterSubscription;

    keyboardDidShowListener = Keyboard.addListener(
      "keyboardDidShow",
      keyboardDidShow
    );

    return () => {
      if (keyboardDidShowListener) {
        keyboardDidShowListener.remove();
      }
    };
  });

  const keyboardDidShow = (e: any) => {
    setVisible(false);
    setHeight(e.endCoordinates.height); // sets the height after opening the keyboard
  };

  const openEmojiPicker = () => {
    Keyboard.dismiss();
    setVisible(true);
  };

  const openKeyboard = () => {
    setVisible(false);
    inputRef.current!.focus();
  };

  return (
    <KeyboardAvoidingView style={styles.container} behavior="height" enabled>
      <View style={styles.inputToolBar}>
        <Button
          title={visible ? "Open keyboard" : "Open emoji picker"}
          onPress={visible ? openKeyboard : openEmojiPicker}
        />
        <TextInput placeholder="test" ref={inputRef} />
      </View>
      <View style={[styles.emojiPicker, { height: visible ? height : 0 }]} />
    </KeyboardAvoidingView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    position: "absolute",
    bottom: 0,
    left: 0,
    right: 0
  },
  inputToolBar: {
    flexDirection: "row"
  },
  emojiPicker: {
    backgroundColor: "red"
  }
});

export default App;

推荐答案

我不知道一个非常干净的方法来做到这一点,但你可以显示键盘,获取高度,然后用你的视图替换键盘.

I don't know a very clean way to do this, but you could show the keyboard, get the height, then replace the keyboard with your view.

这篇关于如何在 React Native 中获得“打开前的键盘高度"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆