<View>
<View style = {{height : X}}></View>
<ScrollView>
<KeyboardAvoidingView>
<View style = {{height : 350}}></View>
<TextInput/>
<View style = {{height : 500}}></View>
</KeyboardAvoidingView>
</ScrollView>
</View>
当我点击TextInput
时,它向上滚动,但是停在应该位于X下方的位置,这意味着它仍然隐藏在键盘下面。
实际上,问题不在于KeyboardAvoidingView,因为不使用它也会发生
答案 0 :(得分:2)
这就是我解决此问题的方法
<KeyboardAvoiding behavior={'padding'} keyboardVerticalOffset={64} style={styles.container}>
<View style={styles.container}>
<ScrollView keyboardShouldPersistTaps="always">
<View style = {{height : 350}}></View>
<TextInput/>
<View style = {{height : 500}}></View>
</ScrollView>
</View>
</KeyboardAvoiding>
container: {
flex: 1,
alignItems: 'center',
}
这是KeyboardAvoiding类
import React from 'react'
import { Platform, KeyboardAvoidingView as ReactNativeKeyboardAvoidingView } from 'react-native'
class KeyboardAvoidingView extends React.Component {
render() {
if (Platform.OS === 'ios') {
return (
<ReactNativeKeyboardAvoidingView behavior={'padding'} {...this.props}>
{this.props.children}
</ReactNativeKeyboardAvoidingView>
)
}
return this.props.children
}
}
KeyboardAvoidingView.propTypes = {
children: React.PropTypes.element,
}
module.exports = KeyboardAvoidingView
希望这会有所帮助。
答案 1 :(得分:0)
render() {
var a = [];
for(var i =1; i< 100; i++) a.push(i);
return (
<View>
<Button title = 'Scroll' onPress = {() => this.refs.scroll.scrollTo({x: 0, y: 0, animated: true})}/>
<ScrollView ref = 'scroll'>{a.map((item, index) => (<TextInput style = {{height : 10 + (Math.floor(Math.random() * 10) * 5)}}
placeholder = {item + ''}
onFocus = {() => {
this.refs.scroll.scrollTo({x : 0, y : this.y[index], animated : true});
}}
onLayout = {event => {
this.y[index] = event.nativeEvent.layout.y;
}}
/>))}</ScrollView>
</View>
);
}
使用此解决方案,存在2个缺点,这些缺点会引发其他需要解决的问题
TextInput
在FlatList
内或间接包含TextInput
的某些组件中的情况。在这种情况下,event.nativeEvent.layout.y
将始终返回0。多层ScrollView
没问题。暂时的解决方案是避免将TextInput
放在prop组件内TextInput
的偏移量不是ScrollView
,则相对于包装器组件。如果包装器不在ScrollView的顶部,则滚动距离必须是TextInput
的偏移量和包装器的偏移量的总和。由于父项的布局后数据无法在渲染之前直接通过prop传递给子项,因此TextInput
必须在其onFocus
处理程序中获取包装器的偏移量onFocus
之后采取措施,从而取消onFocus
的效果。临时解决方案是使用setTimeout
来延迟onFocus
动作至少200毫秒