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

标签 react-native native-base

enter image description here

上面的黄色区域是 Textarea 和一个按钮面板,预计会始终粘在屏幕底部。然而,当用户尝试输入时,键盘将阻止 View ,如下所示

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' }
});

最佳答案

我找到了解决它的方法。用额外的 View 包装 KeyboardAvoidingView,并实现 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}>
    ...
  </KeyboardAvoidingView>
</View>

关于react-native - 如何在全屏模式下使用 KeyboardAvoidingView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53497908/

相关文章:

react-native - 重复的模块名称 : react-native-vector-icons

android - 如何删除原生选项卡的边框

react-native - 使用 Native Base Toast 显示来自 Redux 操作的错误

android - 任务 ':app:mergeDebugResources' 执行失败。 react native,目前正在尝试在Android上运行

typescript - React Navigation V5 + Typescript 错误 : Property 'fullName' does not exist on type 'object'

javascript - 当所有屏幕通过 React Navigation 获得焦点时,在每个屏幕上执行相同的功能

css - React Native Nativebase如何让Picker向右浮动

javascript - 如何防止组件随着 View 的增长而向上移动

javascript - React Native 组件未在 map() 迭代器内渲染

javascript - React Native <ListItem onPress={...}> - 为什么要执行此函数?