In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "what is the knowledge of Refs". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn "what is the knowledge of Refs"?
Refs provides a way for us to access DOM nodes or React elements created in the render method.
Refs usage scenario
In some cases, we need to force the modification of a subcomponent outside of a typical data flow, which may be an instance of a React component or a DOM element, such as:
Manage focus, text selection or media playback.
Triggers a forced animation.
Integrate third-party DOM libraries.
Set up Refs
1. CreateRef
Support for use within function components and class components
CreateRef is introduced in the React16.3 version.
Create Refs
Create a Refs using React.createRef () and attach it to the React element through the ref attribute. Typically in the constructor, the Refs is assigned to the instance property for reference throughout the component.
Visit Refs
When a ref is passed to an element in render, a reference to that node can be accessed in the current attribute of the ref.
Import React from 'react'; export default class MyInput extends React.Component {constructor (props) {super (props); / / assigned to the instance attribute this.inputRef = React.createRef (null);} componentDidMount () {/ / get the reference to the node this.inputRef & & this.inputRef.current.focus () through this.inputRef.current } render () {/ / associate ref with return ()} on `inputRef` created in the constructor
The value of ref varies depending on the type of node:
When the ref attribute is used for the HTML element, the ref created with React.createRef () in the constructor receives the underlying DOM element as its current attribute.
When the ref property is used for a custom class component, the ref object receives the mounted instance of the component as its current property.
You cannot use the ref property on a function component because the function component does not have an instance.
Summary: add a ref to the DOM, so we can get a reference to the DOM node through ref. By adding ref to the React component, we can get the instance of the component through ref [you cannot use the ref property on the function component because the function component does not have an instance].
2. UseRef
Use only within function components
UseRef is introduced in React16.8 and can only be used in function components.
Create Refs
Create a Refs using React.useRef () and attach it to the React element through the ref attribute.
Const refContainer = useRef (initialValue)
The ref object returned by useRef remains unchanged throughout the lifecycle of the component.
Visit Refs
When the ref is passed to the React element, the reference to that node can be accessed in the current attribute of the ref.
Import React from 'react'; export default function MyInput (props) {const inputRef = React.useRef (null); React.useEffect (() = > {inputRef.current.focus ();}); return ()}
With regard to the fact that the ref object returned by React.useRef () remains unchanged throughout the life cycle of the component, let's compare it with React.createRef (). The code is as follows:
Import React, {useRef, useEffect, createRef, useState} from 'react'; function MyInput () {let [count, setCount] = useState (0); const myRef = createRef (null); const inputRef = useRef (null); / / execute useEffect (() = > {inputRef.current.focus (); window.myRef = myRef; window.inputRef = inputRef;}, []) only once UseEffect (() = > {/ / except for the first time it is true, every time is false [createRef] console.log ('myRef = window.myRef', myRef = window.myRef); / / always true [useRef] console.log (' inputRef = window.inputRef', inputRef = window.inputRef) }) return (setCount (count+1)} > {count})}
3. Callback Refs
Support for use within function components and class components
React supports setting Refs by calling back refs. This approach can help us control more finely when the Refs is set and removed.
Using the callback refs requires passing the callback function to the ref attribute of the React element. This function takes a React component instance or HTML DOM element as a parameter and mounts it to the instance property, as shown below:
Import React from 'react'; export default class MyInput extends React.Component {constructor (props) {super (props); this.inputRef = null; this.setTextInputRef = (ele) = > {this.inputRef = ele;}} componentDidMount () {this.inputRef & & this.inputRef.focus () } render () {return ()}}
React will call the ref callback function and pass in the DOM element (or React instance) when the component is mounted, and call it and pass null when unloading. Before componentDidMoune or componentDidUpdate is triggered, React ensures that Refs is up-to-date.
You can pass refs in callback form between components.
Import React from 'react'; export default function Form () {let ref = null; React.useEffect (() = > {/ / ref is the input node ref.focus () in MyInput;}, [ref]) Return (ref = ele} / > {/ * * other code * /})} function MyInput (props) {return ()}
4. String Refs (obsolete API)
The string refs is not supported inside function components [support createRef | useRef | callback Ref]
Function MyInput () {return ()}
Class component
Get the React element through this.refs.XXX.
Class MyInput extends React.Component {componentDidMount () {this.refs.inputRef.focus ();} render () {return ()}}
Ref transfer
Before Hook, high-level components (HOC) and render props were the main means of reusing component logic in React.
Although the convention for high-level components is to pass all props to the wrapped component, refs is not passed. In fact, ref is not a prop. Like key, it is handled specifically by React.
This problem can be solved by React.forwardRef (new in React 16.3). Before React.forwardRef, we can do this by adding forwardedRef to the container component (the name of prop is determined by ourselves, but it cannot be ref or key).
Before React.forwardRef
Import React from 'react'; import hoistNonReactStatic from' hoist-non-react-statics' Const withData = (WrappedComponent) = > {class ProxyComponent extends React.Component {componentDidMount () {/ / code} / / when using, we need to know that this component is the wrapped component / / passing the ref value to forwardedRef's prop render () {const {forwardedRef,... remainingProps} = this.props Return ()}} / / specify displayName. Static methods are not copied (not for HOC) ProxyComponent.displayName = WrappedComponent.displayName | | WrappedComponent.name | | 'Component'; / / copy non-React static methods hoistNonReactStatic (ProxyComponent, WrappedComponent); return ProxyComponent;}
In this example, we pass the property value of ref to the wrapped component through forwardedRef's prop, using:
Class MyInput extends React.Component {render () {return ()} MyInput = withData (MyInput); function Form (props) {const inputRef = React.useRef (null) React.useEffect (() = > {console.log (inputRef.current)}) / / when using MyInput, we need to distinguish whether it is a packaged component to determine whether to specify ref or forwardedRef return ()}
React.forwardRef
Ref forwarding is a technique that automatically passes ref through components to one of its subcomponents, allowing certain components to receive ref and pass it down to subcomponents.
Forward ref to DOM:
Import React from 'react'; const MyInput = React.forwardRef ((props, ref) = > {return ()}); function Form () {const inputRef = React.useRef (null); React.useEffect () = > {console.log (inputRef.current); / / input Node}) return ()}
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Calling React.useRef creates a React ref and assigns it to the ref variable.
Specify ref as the JSX attribute and pass it down
React passes ref to the function in forwardRef (props, ref) = >. As its second parameter.
Forward the ref parameter down to and specify it as the JSX property
When the ref mount is complete, inputRef.current points to the input DOM node
Be careful
The second parameter, ref, exists only when you use React.forwardRef to define a component. Regular functions and class components do not receive ref parameters, and there is no ref in props.
Before React.forwardRef, if we want to pass the ref attribute to the child component, we need to distinguish whether the component is wrapped by HOC or not, which causes some inconvenience to use. Let's use React.forwardRef refactoring.
Import React from 'react'; import hoistNonReactStatic from' hoist-non-react-statics'; function withData (WrappedComponent) {class ProxyComponent extends React.Component {componentDidMount () {/ / code} render () {const {forwardedRef,... remainingProps} = this.props Return ()}} / / when using components wrapped by withData, we only need to pass ref to const forwardRef = React.forwardRef ((props, ref) = > ()); / / specify displayName. ForwardRef.displayName = WrappedComponent.displayName | | WrappedComponent.name | | 'Component'; return hoistNonReactStatic (forwardRef, WrappedComponent);} class MyInput extends React.Component {render () {return ()}} MyInput.getName = function () {console.log (' name');} MyInput = withData (MyInput); console.log (MyInput.getName) / / Test whether the static method copy is normal function Form (props) {const inputRef = React.useRef (null); React.useEffect (() = > {console.log (inputRef.current); / / packaged component MyInput}) / / when in use, pass ref to return ()}
An example of getting sub-components (packaged puppet components) in react-redux
In the old version (V4 / V5)
We know that connect has four parameters, and if we want an instance of the child component (puppet component) of the parent component, we need to set the withRef of the fourth parameter, options, to true. You can then obtain an instance of the puppet component (the wrapped component) in the parent component through the getWrappedInstance () method of the container component instance, as shown below:
/ / MyInput.js import React from 'react'; import {connect} from' react-redux'; class MyInput extends React.Component {render () {return ()}} export default connect (null, {withRef: true}) (MyInput); / / index.js import React from "react"; import ReactDOM from "react-dom"; import {createStore} from 'redux'; import {Provider} from' react-redux' Import MyInput from'. / MyInput'; function reducer (state, action) {return state;} const store = createStore (reducer); function Main () {let ref = React.createRef (); React.useEffect () = > {console.log (ref.current.getWrappedInstance ()) }) return ()} ReactDOM.render (, document.getElementById ("root"))
It is important to note here that MyInput must be a class component, and a function component does not have an instance, so it is naturally impossible to get its instance through ref. In the react-redux source code, getWrappedInstance returns the instance this.refs.wrappedInstance by adding a ref attribute to the wrapped component.
If (withRef) {this.renderedElement = createElement (WrappedComponent, {... this.mergedProps, ref: 'wrappedInstance'})}
New version (V6 / V7)
The new version of react-redux uses the React.forwardRef method for ref forwarding. Since version V6, withRef in option has been discarded. If you want to obtain an instance of a packaged component, you need to specify that the forwardRef of option, the fourth parameter of connect, is true. For more information, please see the following example:
/ / MyInput.js file import React from 'react'; import {connect} from' react-redux'; class MyInput extends React.Component {render () {return ()}} export default connect (null, {forwardRef: true}) (MyInput)
Directly add ref to the wrapped component, and you can get the instance of the wrapped component, as shown below:
/ / index.js import React from "react"; import ReactDOM from "react-dom"; import {createStore} from 'redux'; import {Provider} from' react-redux'; import MyInput from'. / MyInput'; function reducer (state, action) {return state;} const store = createStore (reducer); function Main () {let ref = React.createRef (); React.useEffect () = > {console.log (ref.current) }) return ()} ReactDOM.render (, document.getElementById ("root"))
Similarly, MyInput must be a class component, because a function component does not have an instance, and it is naturally impossible to get its instance through ref.
Ref is forwarded to the Connect component in react-redux. The ref that is passed to the wrapped component WrappedComponent through forwardedRef.
If (forwardRef) {const forwarded = React.forwardRef (function forwardConnectRef (props, ref) {return}) forwarded.displayName = displayName forwarded.WrappedComponent = WrappedComponent return hoistStatics (forwarded, WrappedComponent)} / /. Const {forwardedRef,... wrapperProps} = props const renderedWrappedComponent = useMemo (() = >, [forwardedRef, WrappedComponent, actualChildProps]) so far, I believe you have a deeper understanding of "what is the knowledge of Refs", you might as well do it in practice! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.