What are refs in React?

前端 未结 4 690
终归单人心
终归单人心 2021-02-09 05:38

I\'m having trouble understanding what refs are in React. I understand that it\'s a callback function and you put it in the render function, but beyond that I can\'t understand

4条回答
  •  情歌与酒
    2021-02-09 06:09

    Refs are a way to set a variable at a DOM element or a class component instance.

    There are two types of refs: callback refs, and object refs.

    Object Refs

    Object refs are created using useRef() or React.createRef().

    To use them (an example with a function component referencing a DOM element):

    1. Declare a "container" variable (which you will point at a DOM element in the next step) and set it equal to useRef(). This is your "ref object."

    2. Add a ref attribute to your DOM element. Set it equal to your ref object.

    3. Now this ref object represents the DOM element you pointed it at, and can be used to access its methods and properties.

      function InputField() {
          const refForInput = useRef(); // 1. initializing `refForInput` as a reference object.
          return (
              
      //2. passing it to the input element as its ref // 3. now, calling `refForInput` will refer to the DOM element, and you can access its `focus()` method.
      ) }

    The process is similar if using class components; see the React docs for details.

    Callback Refs

    Callback refs function similarly, but allow more fine-grained control.

    To create a callback ref, you similarly add a ref attribute to your DOM element, but instead of passing in a ref object, you pass in a callback. This callback receives the element itself as the argument for the callback; you can then set it equal to an existing value (this.something in a class; an already-declared variable in a function component.)

    Here's an annotated vversion of the example from Avid Programmer's excellent example; see his answer for an example with classes.

        function CustomForm({handleSubmit}) {
            let inputElement;
            return (
                
    handleSubmit(inputElement.value)}> // 2. Now, this refers to the `value` of the `` element just below. inputElement = input} // 1. so, here, `input` in the callback refers to the DOM element. Now, when the component mounts, `inputElement` will *reference* this DOM element. />
    ) }

    Note that the callback will be called with null when the component unmounts.

    Why are they useful?

    They shouldn't be used often; they're meant as escape hatches. They allow you to access API methods (focus() is a common example) available on the actual html elements that may not be available on the React component. If this seems confusing, remember that a React button component, for example, is not the same as an html button component. You can call focus() on an html button element, but not on a React button element.

提交回复
热议问题