React refs how are they used, and when are they used?

前端 未结 2 1402
青春惊慌失措
青春惊慌失措 2021-01-23 17:06

Hello and thank you for reading this question!

I have been learning React for some weeks and I have difficulties trying to understand how refs

2条回答
  •  旧巷少年郎
    2021-01-23 17:29

    React supports a special attribute that you can attach to any component. The ref attribute takes a callback function, and the callback will be executed immediately after the component is mounted or unmounted.

    When you write

     { this.textInput = input; }} />
    

    React extracts the ref attribute and invokes a callback after the component is mounted. In that callback function react passes the instance of the input, which is what you get as the parameter here. Think of the above as a function

    
    

    and that callback will look like

    const callback = (input) => { 
       this.textInput = input; 
    }
    

    According to the docs:

    When the ref attribute is used on an HTML element, the ref callback receives the underlying DOM element as its argument.

    Regarding your next question:

    However I do not understand why the parameter being passed to the refs is (input) what could happen if there were jsx tags nested

    The parameter being passed to div is just referenced as input in your example, you can call it anything you want, like input, inputRef, instance

    In multiple jsx tags are nested, the ref is applied on the element on which ref attribute is passed. For instance

    Hello React

    The ref gets the instance of is applied to the outer div from which you can access the child elements.

    Codesandbox

    Also is there not a clear way to reference the elements being created with React render/return

    Well refs is a way provided by React to reference, elements being created. However you should only use refs when

    • Managing focus, text selection, or media playback.
    • Triggering imperative animations.
    • Integrating with third-party DOM libraries.

    Most often, props are the only way that parent components interact with their children. To modify a child, you re-render it with new props. For example if you wish to change the class on an element, instead of getting an access to the element and changing it class, you would pass the dynamic prop to it instead like

    Or as a matter of fact, use state to make necessary updates

提交回复
热议问题