如何在React Native中将TextInput与键盘绑定

4
我正在使用react-native构建一个面向iOS和Android的应用程序。其中一项任务是创建一个与键盘连接的文本输入框。它的工作方式是TextInput位于屏幕底部。当用户触摸它时,键盘会打开,并且TextInput会以与键盘同样的速度上下移动(因为它们相互连接)。目前,我正在使用onKeyboardWillShow和onKeyboardWillHide来实现这一点,并对TextInput进行动画处理。问题是它们不能以相同的速度移动。基本上,我正在尝试做到这一点:https://github.com/Just-/UIViewController-KeyboardAnimation。任何建议都将有所帮助。
2个回答

4

使用 React Native 的键盘避免视图 KeyboardAvoidingView示例。像这样:

import {ScrollView, Text, TextInput, View, KeyboardAvoidingView} from "react-native";

在渲染函数中嵌套ViewTextInput
<KeyboardAvoidingView behavior='padding'>
  <View style={styles.textInputContainer}>
    <TextInput
      value={this.state.data}
      style={styles.textInput}
      onChangeText={this.handleChangeData}
    />
  </View>
</KeyboardAvoidingView>

它将会处理那个问题。


3

我能找到的最接近键盘动画的方法是使用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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接