Refs in ReactJS || ReactJS Tutorials

Publié le: 14 juillet 2018
sur la chaîne: Tech Talk
160
3

Refs provide a way to access DOM nodes or React elements created in the render method.
Generally, the use of refs should be considered only when the required interaction cannot be achieved using the mechanisms of state and props.
You may not use the ref attribute on functional components because they don’t have instances. You should convert the component to a class if you need a ref to it, just like you do when you need lifecycle methods or state.

React provides three major ways of creating refs
1. String refs (deprecated)
2. Callback refs
3. createRef

createRef() API introduced in React 16.3. If you are using an earlier release of React, we recommend to use callback refs instead.

If the ref callback is defined as an inline function, it will get called twice during updates, first with null and then again with the DOM element. This is because a new instance of the function is created with each render, so React needs to clear the old ref and set up the new one. You can avoid this by defining the ref callback as a bound method on the class, but note that it shouldn’t matter in most cases.

When to use refs
-------------------------------
There are a few good use cases for refs:
1. Managing focus, text selection, or media playback.
2. Triggering imperative animations.
3. Integrating with third-party DOM libraries.

Avoid using refs for anything that can be done declaratively.


Sur cette page du site, vous pouvez voir la vidéo en ligne Refs in ReactJS || ReactJS Tutorials durée heure minute seconde en bonne qualité , qui a été Téléchargé par l'utilisateur Tech Talk 14 juillet 2018, Partagez le lien avec vos amis et connaissances, sur youtube cette vidéo a déjà été regardée 160 fois et il a aimé 3 téléspectateurs. Bon visionnage!