当 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屋!