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

What are Refs used for in React Native?

Câu trả lời

Refs in React Native are used to directly access and manipulate DOM nodes or React Native components created in the render method. They provide a way to interact with elements without using state or props, which can be particularly useful for certain tasks that require direct DOM manipulation.

Key Uses of Refs in React Native

  1. Managing Focus and Text Selection:

    • Refs can be used to programmatically focus on input fields or select text within them. For example, you can shift the focus to a TextInput component when a button is pressed by using a ref to call the focus method on the TextInput component[1][2].
  2. Accessing DOM Nodes:

    • Refs allow you to access and interact with DOM nodes directly. This is useful for integrating with third-party libraries that require direct DOM manipulation, such as jQuery or other vanilla JavaScript libraries[4].
  3. Changing Native Properties:

    • In React Native, refs can be used to change native properties of components without triggering a re-render. For instance, you can use the setNativeProps method to update properties like editable on a TextInput component[2][7].
  4. Storing Mutable Values:

    • Refs can hold onto values that need to persist across renders without causing re-renders. This is useful for storing mutable values like interval IDs or other non-visual data[5][6].

Creating and Using Refs

Refs can be created in several ways:

  • Using useRef Hook:

    import React, { useRef } from 'react';
    function MyComponent() {
      const inputRef = useRef(null);
      return <TextInput ref={inputRef} />;
    }
  • Using createRef Method:

    class MyComponent extends R...
junior

junior

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

junior

What are props in React Native?

junior

What are the advantages of native apps over hybrid apps?

expert

How does the Fabric architecture work?

Bình luận

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

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