我已经看到了 native 应用程序自动滚动窗口的技巧,但想知道在 React Native 中执行此操作的最佳方法...当 <TextInput>
字段获得焦点并位于 View 中的较低位置,键盘将覆盖文本字段。
您可以在 UIExplorer 的示例 TextInputExample.js
中看到此问题看法。
谁有好的解决办法吗?
最佳答案
2017 年答案
KeyboardAvoidingView
可能是现在最好的方法。查看文档 here 。与 Keyboard
模块相比,它非常简单,它为开发人员提供了更多控制来执行动画。 Spencer Carli 在 his medium blog 上演示了所有可能的方法.
2015 年答案
在 react-native
中执行此操作的正确方法不需要外部库,利用 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 设计的需求。
关于javascript - 当 TextInput 获得焦点时,如何自动将窗口从键盘后面滑出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29313244/