Câu hỏi phỏng vấn React Native
Câu hỏi

How do you dismiss the keyboard in react native?

Câu trả lời

To dismiss the keyboard in a React Native application, there are several methods you can use. Here are the most common approaches:

1. Using 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();

2. Using 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].

3. Using 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

junior

Gợi ý câu hỏi phỏng vấn

middle

What does TouchableHighlight do and when do you use it?

junior

What determines the size of a component and what are the ways?

expert

What is wrong with this code for querying a native API?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào