gpt4 book ai didi

react-native - 如何在 React Native 中获取 'Keyboard height before it opens'?

转载 作者:行者123 更新时间:2023-12-03 17:13:22 28 4
gpt4 key购买 nike

环境:

react 原生 0.60.4

问题:

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

My ultimate goal

示例:

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;

最佳答案

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

关于react-native - 如何在 React Native 中获取 'Keyboard height before it opens'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57447880/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com