如何在全屏模式下使用KeyboardAvoidingView?

时间:2018-11-27 10:45:26

标签: react-native native-base

enter image description here

上面的黄色区域是Textarea,预计会有一个按钮面板一直粘附在屏幕底部。但是,当用户尝试键入内容时,键盘会阻止该视图,如下所示

enter image description here

我已经实现了KeyboardAvoidingView,但未能使按钮显示在键盘上方。

我的代码如下:

  <KeyboardAvoidingView behavior="padding" style={{ flex: 1 }}>
    <Container style={Styles.containerStyle}>
      <Textarea 
        autoCapitalize="none"
        autoCorrect={false}
        style={Styles.textAreaStyle}
      />
      <View style={Styles.buttonPanelStyle}>
        <Button style={Styles.buttonStyle}><Text>CANCEL</Text></Button>
        <Button style={Styles.buttonStyle}><Text>SAVE</Text></Button>
      </View>
    </Container>
  </KeyboardAvoidingView>


const Styles = StyleSheet.create({
  containerStyle: { backgroundColor: 'green' },
  textAreaStyle: { backgroundColor: 'yellow', flex: 1 },
  buttonPanelStyle: { backgroundColor: 'red', flexDirection: 'row' },
  buttonStyle: { flex: 1, justifyContent: 'center' }
});

1 个答案:

答案 0 :(得分:0)

我找到了解决它的方法。用额外的KeyboardAvoidingView包装View,并实现onLayout以重新计算屏幕的高度。示例代码如下:

const { height: fullHeight } = Dimensions.get('window');
...
onLayout = ({
  nativeEvent: { layout: { height } },
}) => {
  const offset = fullHeight - height;
  this.setState({ offset });
}
...
<View style={{ flex: 1 }} onLayout={this.onLayout}>
  <KeyboardAvoidingView behavior="padding" style={{ flex: 1 }} keyboardVerticalOffset={this.state.offset}>
</View>