3 回答
TA贡献1840条经验 获得超5个赞
这KeyboardAvoidingView可能是现在最好的方法。在此处查看文档。与Keyboard提供开发人员更多控制权以执行动画的模块相比,它确实非常简单。斯宾塞·卡利(Spencer Carli)在他的中型博客上展示了所有可能的方式。
2015年答案
这样做的正确方法react-native不需要外部库,可以利用本机代码并包含动画。
首先定义一个函数,该函数将处理onFocus每个事件TextInput(或您要滚动到的任何其他组件)的事件:
// 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设计的需求。
TA贡献1836条经验 获得超4个赞
我们结合了一些代码形式react-native-keyboard-spacer和@Sherlock中的代码,以创建一个KeyboardHandler组件,该组件可以包装在带有TextInput元素的任何View周围。奇迹般有效!:-)
/**
* Handle resizing enclosed View and scrolling to input
* Usage:
* <KeyboardHandler ref='kh' offset={50}>
* <View>
* ...
* <TextInput ref='username'
* onFocus={()=>this.refs.kh.inputFocused(this,'username')}/>
* ...
* </View>
* </KeyboardHandler>
*
* offset is optional and defaults to 34
* Any other specified props will be passed on to ScrollView
*/
'use strict';
var React=require('react-native');
var {
ScrollView,
View,
DeviceEventEmitter,
}=React;
var myprops={
offset:34,
}
var KeyboardHandler=React.createClass({
propTypes:{
offset: React.PropTypes.number,
},
getDefaultProps(){
return myprops;
},
getInitialState(){
DeviceEventEmitter.addListener('keyboardDidShow',(frames)=>{
if (!frames.endCoordinates) return;
this.setState({keyboardSpace: frames.endCoordinates.height});
});
DeviceEventEmitter.addListener('keyboardWillHide',(frames)=>{
this.setState({keyboardSpace:0});
});
this.scrollviewProps={
automaticallyAdjustContentInsets:true,
scrollEventThrottle:200,
};
// pass on any props we don't own to ScrollView
Object.keys(this.props).filter((n)=>{return n!='children'})
.forEach((e)=>{if(!myprops[e])this.scrollviewProps[e]=this.props[e]});
return {
keyboardSpace:0,
};
},
render(){
return (
<ScrollView ref='scrollView' {...this.scrollviewProps}>
{this.props.children}
<View style={{height:this.state.keyboardSpace}}></View>
</ScrollView>
);
},
inputFocused(_this,refName){
setTimeout(()=>{
let scrollResponder=this.refs.scrollView.getScrollResponder();
scrollResponder.scrollResponderScrollNativeHandleToKeyboard(
React.findNodeHandle(_this.refs[refName]),
this.props.offset, //additionalOffset
true
);
}, 50);
}
}) // KeyboardHandler
module.exports=KeyboardHandler;
添加回答
举报