Home  >  Article  >  Web Front-end  >  What is ref in react

What is ref in react

藏色散人
藏色散人Original
2021-02-01 09:13:195967browse

ref is the interface provided by React for manipulating React component instances or DOM elements; the callback function is to mount a function on the dom node or component, and the input parameter of the function is the dom node or component instance to achieve the desired effect It is the same as the string form, and its reference is obtained.

What is ref in react

In the typical data flow of react, props passing is the only way for parent and child components to interact; by passing a new props value, the child component Rere-render to achieve parent-child component communication. Of course, as described on the react official website, in addition to the typical amount of data in react, in some cases (such as integrating with a third-party dom library, or focusing on a certain dom element, etc.) we may need to modify sub-components. One way, this is the ref way.

ref Introduction

The ref attribute provided by React, represents a reference to the real instance of the component, which is actually what ReactDOM.render() returns Component instance; It needs to be distinguished. ReactDOM.render()When rendering a component, it returns a component instance; when rendering a dom element, it returns a specific dom node.

For example, the following code:

    const domCom = <button>button</button>;
    const refDom = ReactDOM.render(domCom,container);
    //ConfirmPass的组件内容省略
    const refCom = ReactDOM.render(<confirmpass></confirmpass>,container);
    console.log(refDom);
    console.log(refCom);

The above code returns the console result as shown below:

What is ref in react

refCan be hung on any component, either on a component or on a dom element; the difference between the two is the same as the answer in the above picture:

Hung on the component (here the component refers to the stateful one) The ref on the component) represents a reference to the component instance, and when mounted on a dom element, it represents a specific dom element node.

ref can be set to a callback function

The ref attribute can be set to a callback function, which is also the officially recommended usage; the timing of this function execution is:

  • After the component is mounted, the callback function is executed immediately, and the parameter of the callback function is the specific instance of the component.

  • When the component is uninstalled or the original ref attribute itself changes, the callback will also be executed immediately. At this time, the callback function parameter is null to ensure memory leaks.

Related recommendations: "react tutorial"

For example, the following code:

    RegisterStepTwo = React.createClass({
        getInitialState(){
          return {visible: true};
        },
      changeVisible(){
        this.setState({visible: !this.state.visible});
      },
      refCb(instance){
        console.log(instance);
      },
      render(){
        return(
          <p>
            <button>{this.state.visible ? '卸载' : '挂载'}ConfirmPass
            </button>
            {
              this.state.visible ?
                <confirmpass></confirmpass>: null
             }
           </p>
         )
      }
    });

The above code can be rendered to the page It is found that the console.log outputs the corresponding component instance. When the button is switched, ConfirmPass also switches between mounting and unmounting, so different console.log results can be seen.

ref can be set to a string

ref can also be set to a string value instead of a callback function; this method is basically not recommended or will no longer be supported in future react versions This method, but you can understand it.

For example, the following input sets the value of ref to a string.

<input>

Then the component instance can be accessed in other places such as event callbacks through this.refs.input, which is actually the dom element node.

let inputEl = this.refs.input;
//然后通过inputEl来完成后续的逻辑,如focus、获取其值等等

Get the dom node corresponding to the ref reference component

No matter the ref setting value is a callback function or a string, you can get the component through ReactDOM.findDOMNode(ref) The real dom node after mounting.

But when using ref for html elements, the ref itself refers to the actual dom node of the element. There is no need to use ReactDOM.findDOMNode(ref) to obtain it. This method is often used in React components. ref on.

Use of ref in stateful components

As mentioned aboverefWhen using react stateful components, ref refers to the instance of the component; so you can Through the ref of the subcomponent, you can access the props, state, refs, and instance methods (non-inherited) of the subcomponent instance. method) etc.

Using ref to access subcomponents may be the following cases:

  • Access a specific dom node of the subcomponent to complete certain logic, through this. refs.childComponentRefName.refs.someDomRefName to complete, such as the question raised by the questioner on segmentfault.

  • You can access the public instance methods of subcomponents to complete certain writing logic. For example, a child component defines a reset method to reset the child component form element value. At this time, the parent component can complete the child component form through this.refs.childComponentRefName.reset() Reset of elements.

  • ...

But having said that, react does not recommend directly accessing the instance method of the child component in the parent component to complete certain logic , in most cases it will be clearer to use the standard react data flow method instead;

In addition, in the above case, when the component relationship is deeply nested, this method will appear extremely ugly.

ref在无状态组件中的使用

上文说到的react组件都是指有状态的,对于无状态组件stateless component而言,正如这篇文章React创建组件的三种方式及其区别里描述的一样,无状态组件是不会被实例化的,在父组件中通过ref来获取无状态子组件时,其值为null,所以:

无法通过ref来获取无状态组件实例。

虽然无法通过ref获取无状态组件实例,但是可以结合复合组件来包装无状态组件来在其上使用ref引用。

另外,对于无状态组件我们想访问的无非是其中包含的组件或者dom元素,我们可以通过一个变量来保存我们想要的组件或者dom元素组件的实例引用。例如下面代码:

function TestComp(props){
    let refDom;
    return (<p>
        </p><p> refDom = node}>
            ...
        </p>
    )
}

这样,可以通过变量refDom来访问到无状态组件中的指定dom元素了,访问其中的其他组件实例类似。

ref在HOC中存在问题

react的HOC是高阶组件,简单理解就是包装了一个低阶的组件,最后返回一个高阶的组件;高阶组件其实是在低阶组件基础上做了一些事情,比方说antd组件的Form create的方法,它就是在为低阶组件封装了一些特殊的属性,比如form属性。

既然HOC会基于低阶组件生成一个新的高阶组件,若用ref就不能访问到我们真正需要的低阶组件实例,我们访问到的其实是高阶组件实例。所以:

若HOC不做特殊处理,ref是无法访问到低阶组件实例的

要想用ref访问低阶组件实例,就必须得HOC支持,就像Redux的connect方法提供的withRef属性来访问低阶组件一样。具体可以参考这里。

总结

ref提供了一种对于react标准的数据流不太适用的情况下组件间交互的方式,例如管理dom元素focus、text selection以及与第三方的dom库整合等等。 但是在大多数情况下应该使用react响应数据流那种方式,不要过度使用ref。

另外,在使用ref时,不用担心会导致内存泄露的问题,react会自动帮你管理好,在组件卸载时ref值也会被销毁。

最后补充一点:

不要在组件的render方法中访问ref引用,render方法只是返回一个虚拟dom,这时组件不一定挂载到dom中或者render返回的虚拟dom不一定会更新到dom中。

The above is the detailed content of What is ref in react. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn