【问题标题】:How to attach TextInput to the keyboard in react-native如何在 react-native 中将 TextInput 附加到键盘
【发布时间】:2016-04-19 04:15:17
【问题描述】:
【问题讨论】:
标签:
android
ios
keyboard
react-native
【解决方案1】:
使用 react native 的键盘避免视图
KeyboardAvoidingView 和 Example
喜欢
import {ScrollView, Text, TextInput, View, KeyboardAvoidingView} from "react-native";
在渲染函数中嵌套View和TextInput
<KeyboardAvoidingView behavior='padding'>
<View style={styles.textInputContainer}>
<TextInput
value={this.state.data}
style={styles.textInput}
onChangeText={this.handleChangeData}
/>
</View>
</KeyboardAvoidingView>
它会解决这个问题
【解决方案2】:
我最接近键盘动画的是使用LayoutAnimation:
import React, { LayoutAnimation } from 'react-native';
componentWillMount() {
DeviceEventEmitter.addListener('keyboardWillShow', this.keyboardWillShow.bind(this));
DeviceEventEmitter.addListener('keyboardWillHide', this.keyboardWillHide.bind(this));
}
keyboardWillShow(e) {
const visibleHeight = Dimensions.get('window').height - e.endCoordinates.height;
LayoutAnimation.configureNext(LayoutAnimation.create(
e.duration,
LayoutAnimation.Types[e.easing]
));
this.setState({ visibleHeight });
}
this.state.visibleHeight 管理整个 <View> 容器高度。
当然不要忘记停止监听键盘事件:
componentWillUnmount() {
DeviceEventEmitter.removeAllListeners('keyboardWillShow');
DeviceEventEmitter.removeAllListeners('keyboardWillHide');
}
Cf AnimationsLayout 源代码:https://github.com/facebook/react-native/blob/60db876f666e256eba8527251ce7035cfbca6014/Libraries/LayoutAnimation/LayoutAnimation.js#L26