当TextInput具有焦点时,如何从键盘后面自动滑动窗口? [英] How to auto-slide the window out from behind keyboard when TextInput has focus?
问题描述
我已经看到了本机应用程序可以自动滚动窗口的一种方法,但是我想知道在React Native中实现此目的的最佳方法...当<TextInput>
字段获得焦点并位于视图的下方时,键盘将掩盖文本字段.
I've seen this hack for native apps to auto scroll the window, but wondering best way to do it in React Native... When a <TextInput>
field gets focus and is positioned low in the view, the keyboard will cover up the text field.
您可以在示例UIExplorer的TextInputExample.js
视图中看到此问题.
You can see this issue in example UIExplorer's TextInputExample.js
view.
有人能找到好的解决方案吗?
Does anyone have a good solution?
推荐答案
2017年答案
KeyboardAvoidingView
可能是现在最好的选择.在此处中查看文档.与Keyboard
模块相比,它确实很简单,它为开发人员提供了更多控制权来执行动画. Spencer Carli 在
The KeyboardAvoidingView
is probably the best way to go now. Check out the docs here. It is really simple compared to Keyboard
module which gives Developer more control to perform animations. Spencer Carli demonstrated all the possible ways on his medium blog.
2015年答案
在react-native
中执行此操作的正确方法不需要外部库,可以利用本机代码并包含动画.
The correct way to do this in react-native
does not require external libraries, takes advantage of native code, and includes animations.
首先定义一个函数,该函数将为每个TextInput
(或您要滚动到的任何其他组件)处理onFocus
事件:
First define a function that will handle the onFocus
event for each TextInput
(or any other component you would like to scroll to):
// 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);
}
然后,在您的渲染函数中:
Then, in your render function:
render () {
return (
<ScrollView ref='scrollView'>
<TextInput ref='username'
onFocus={this.inputFocused.bind(this, 'username')}
</ScrollView>
)
}
这将RCTDeviceEventEmitter
用于键盘事件和大小调整,使用RCTUIManager.measureLayout
测量组件的位置,并计算scrollResponderInputMeasureAndScrollToKeyboard
中所需的确切滚动移动.
This uses the RCTDeviceEventEmitter
for keyboard events and sizing, measures the position of the component using RCTUIManager.measureLayout
, and calculates the exact scroll movement required in scrollResponderInputMeasureAndScrollToKeyboard
.
您可能需要使用additionalOffset
参数来适应特定UI设计的需求.
You may want to play around with the additionalOffset
parameter, to fit the needs of your specific UI design.
这篇关于当TextInput具有焦点时,如何从键盘后面自动滑动窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!