环境:
React-Native 0.60.4
问题:
我正在开发聊天应用程序。该聊天应用程序有一个表情选择器。表情选择器必须具有与键盘相同的高度。我需要在打开键盘之前获取键盘的高度。我尝试使用键盘监听器,但它们会在键盘打开后才提供高度。我的最终目标是像图片中的那样实现。你如何做到这一点?
示例:
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;