react-native – 当TextInput具有焦点时,如何从键盘后面自动滑出窗口?

我已经看到这个黑客为本机应用程序自动滚动窗口,但想知道做最好的方式做反应本机…当一个字段获得焦点和位置低在视图中,键盘将掩盖文本字段。您可以在示例UIExplorer的TextInputExample.js视图中看到此问题。任何一个有好的解决方案?
在react-native中执行此操作的正确方法不需要外部库,利用本机代码,并包括动画。

首先定义一个函数,它将处理每个TextInput(或任何其他要滚动到的组件)的onFocus事件:

// Scroll a component into view. Just pass the component ref string.
inputFocused (refName) {
  setTimeout(() => {
    let scrollResponder = this.refs.scrollView.getScrollResponder();
    scrollResponder.scrollResponderScrollNativeHandletoKeyboard(
      React.findNodeHandle(this.refs[refName]),110,//additionalOffset
      true
    );
  },50);
}

然后,在你的渲染函数

render () {
  return (
    <ScrollView ref='scrollView'>
        <TextInput ref='username' 
                   onFocus={this.inputFocused.bind(this,'username')}
    </ScrollView>
  )
}

这使用RCTdeviceeventemitter用于键盘事件和大小调整,使用RCTUIManager.measureLayout测量组件的位置,并计算scrollResponderInputMeasureAndScrollToKeyboard中所需的确切滚动移动。

您可能想要使用additionalOffset参数,以适应您的特定UI设计的需要。

相关文章

一、前言 在组件方面react和Vue一样的,核心思想玩的就是组件...
前言: 前段时间学习完react后,刚好就接到公司一个react项目...
前言: 最近收到组长通知我们项目组后面新开的项目准备统一技...
react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...