3 回答

TA貢獻(xiàn)1840條經(jīng)驗(yàn) 獲得超5個(gè)贊
這KeyboardAvoidingView可能是現(xiàn)在最好的方法。在此處查看文檔。與Keyboard提供開(kāi)發(fā)人員更多控制權(quán)以執(zhí)行動(dòng)畫的模塊相比,它確實(shí)非常簡(jiǎn)單。斯賓塞·卡利(Spencer Carli)在他的中型博客上展示了所有可能的方式。
2015年答案
這樣做的正確方法react-native不需要外部庫(kù),可以利用本機(jī)代碼并包含動(dòng)畫。
首先定義一個(gè)函數(shù),該函數(shù)將處理onFocus每個(gè)事件TextInput(或您要滾動(dòng)到的任何其他組件)的事件:
// 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);
}
然后,在您的渲染函數(shù)中:
render () {
return (
<ScrollView ref='scrollView'>
<TextInput ref='username'
onFocus={this.inputFocused.bind(this, 'username')}
</ScrollView>
)
}
這將RCTDeviceEventEmitter用于鍵盤事件和大小調(diào)整,使用來(lái)測(cè)量組件的位置RCTUIManager.measureLayout,并計(jì)算中所需的確切滾動(dòng)移動(dòng)scrollResponderInputMeasureAndScrollToKeyboard。
您可能需要試一試該additionalOffset參數(shù),以適合您特定的UI設(shè)計(jì)的需求。

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超4個(gè)贊
我們結(jié)合了一些代碼形式react-native-keyboard-spacer和@Sherlock中的代碼,以創(chuàng)建一個(gè)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;
添加回答
舉報(bào)