环境:
React-Native 0.60.4
Problem:
我正在开发聊天应用程序。聊天有表情符号选择器。表情符号选择器必须与键盘具有相同的高度。我需要在键盘打开之前获取键盘的高度。我尝试使用键盘侦听器,但它们在打开后给出高度。我的最终目标是如图所示。你是怎样做的?
Example:
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;
我不知道一个非常干净的方法来做到这一点,但你可以显示键盘,获取高度,然后用你的视图替换键盘。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)