React Native-如果ScrollView不在屏幕顶部,则键盘避免不起作用

时间:2018-09-20 13:54:20

标签: react-native

<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,因为不使用它也会发生

2 个答案:

答案 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个缺点,这些缺点会引发其他需要解决的问题

  • 不适用于TextInputFlatList内或间接包含TextInput的某些组件中的情况。在这种情况下,event.nativeEvent.layout.y将始终返回0。多层ScrollView没问题。暂时的解决方案是避免将TextInput放在prop组件内
  • 如果TextInput的偏移量不是ScrollView,则相对于包装器组件。如果包装器不在ScrollView的顶部,则滚动距离必须是TextInput的偏移量和包装器的偏移量的总和。由于父项的布局后数据无法在渲染之前直接通过prop传递给子项,因此TextInput必须在其onFocus处理程序中获取包装器的偏移量
  • 默认的越野车键盘有时避免在onFocus之后采取措施,从而取消onFocus的效果。临时解决方案是使用setTimeout来延迟onFocus动作至少200毫秒