How do you dismiss the keyboard in react native?
How do you dismiss the keyboard in react native?
To dismiss the keyboard in a React Native application, there are several methods you can use. Here are the most common approaches:
Keyboard.dismiss()
The Keyboard
module in React Native provides a method called dismiss()
which can be used to programmatically dismiss the keyboard. This method can be called directly in your code when you want to hide the keyboard.
import { Keyboard } from 'react-native';
// Call this function to dismiss the keyboard
Keyboard.dismiss();
TouchableWithoutFeedback
Another common method is to wrap your main view with a TouchableWithoutFeedback
component and call Keyboard.dismiss()
in the onPress
event. This allows the keyboard to be dismissed when the user taps anywhere outside the input fields.
import React from 'react';
import { View, TextInput, TouchableWithoutFeedback, Keyboard, StyleSheet } from 'react-native';
const App = () => {
return (
<TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}>
<View style={styles.container}>
<TextInput style={styles.input} placeholder="Type here" />
</View>
</TouchableWithoutFeedback>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#ccd2db',
},
input: {
width: 200,
height: 50,
borderWidth: 1,
marginTop: 200,
marginLeft: 100,
},
});
export default App;
This method is effective and ensures that the keyboard is dismissed when the user taps outside the input fields[3][5].
ScrollView
with keyboardShouldPersistTaps
If your layout includes a ScrollView
, you can use the keyboardShouldPersistTaps
prop to control the keyboard behavior. Setting this prop to 'handled'
ensures that the keyboard is dismissed when tapping outside the input fields.
import React from 'react';
import { ScrollView, TextInput, StyleSheet } from 'react-native';
const App = () => {
return (
<ScrollView keyboardShouldPersistTaps='handled' style={styles.container}>...
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào