在React Native中,可以使用KeyboardAvoidingView
组件来避免将键盘遮挡住底部的物品。KeyboardAvoidingView
组件会根据键盘的位置自动调整它的子组件的位置。
下面是一个使用KeyboardAvoidingView
组件的示例代码:
import React from 'react';
import { View, TextInput, KeyboardAvoidingView, StyleSheet } from 'react-native';
const App = () => {
return (
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
content: {
width: '80%',
},
input: {
height: 40,
borderColor: 'gray',
borderWidth: 1,
marginBottom: 20,
paddingHorizontal: 10,
},
});
export default App;
在上面的代码中,我们使用KeyboardAvoidingView
组件包裹了一个TextInput
组件。设置behavior
属性为padding
可以根据键盘的位置自动调整KeyboardAvoidingView
组件的子组件的位置。
注意:KeyboardAvoidingView
组件只在键盘弹出时才会生效,如果键盘没有弹出,子组件的位置不会发生改变。