首页 > 解决方案 > React Native - 如果 ScrollView 不在屏幕顶部,则键盘避免不起作用

问题描述

<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 因为它也会在不使用它的情况下发生

标签: react-native

解决方案


这就是我为解决此问题所做的

<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

希望这可以帮助。


推荐阅读