JIYIK CN >

Current Location:Home > Learning > WEB FRONT-END > React >

React component refs detailed explanation

Author:JIYIK Last Updated:2025/03/02 Views:

As the name implies, ref can be seen as a reference to a component, or as an identifier. As a component attribute, its attribute value can be a string or a function.

In fact, the use of ref is not mandatory. Even in the scenarios where it is applicable, it is not necessary to use it, because the functions implemented by using ref can also be converted into other methods. However, since ref has its applicable scenarios, it means that ref has its own advantages. Regarding this point and the applicable scenarios of ref, the official document says:

After returning the UI structure from the render method, you may want to break out of the constraints of the React virtual DOM and call certain methods on the component instance returned by render. Generally speaking, this is not necessary for the data flow in the application, because the active data (Reactive data) flow always ensures that the latest props are passed to each child output from render(). However, there are still several scenarios where it is necessary or beneficial to use this approach: finding the DOM tag (think of it as a DOM ID) of the rendered component, using React components in a large non-React application, or converting your existing code to React .

Let's look at a scenario like this (the following example is often used to explain ref, so it can be seen that the scenario described below should be relatively classic): through an event, the value of the <input /> element is set to an empty string, and then the <input /> element is focused.

var App = React.createClass({
    getInitialState: function() {
      return {userInput: ''};
    },
    handleChange: function(e) {
      this.setState({userInput: e.target.value});
    },
    clearAndFocusInput: function() {
      this.setState({userInput: ''}); // Set the value to an empty string
                // We want to get focus here     
    },
    render: function() {
      return (
        <div>
          <input
            value={this.state.userInput}
            onChange={this.handleChange}
          />
                    <input type="button"
                      value="Reset And Focus"
                      onClick={this.clearAndFocusInput}
               />
        </div>
      );
    }
  });

In the above example, we have implemented the button to notify the input element to set the value to an empty string, but we have not yet implemented the input element to gain focus. This is a bit difficult to implement because what is returned in render() is not a combination of actual subcomponents, but only a description of a specific instance at a specific time. This sentence feels quite confusing. In fact, render returns a virtual DOM , not a real DOM. Therefore, we do not need to focus only on those components returned from render().

That said, it doesn't help us much in getting the focus. To get the focus, we need to use ref. As mentioned above, there are two types of ref values, one is a string and the other is a callback function.

Ref string attributes

React supports a special property that you can add to any component returned by render (). This means marking the component returned by render() so that you can easily locate the component instance. This is what ref does.

The form of ref is as follows

<input ref="myInput" />

To access this instance, you can access it through this.refs:

this.refs.myInput

In previous versions, we can access the component's DOM through React.findDOMNode(this.refs.myInput). But now, the findDOMNode function has been abandoned, and you can directly use this.refs.myInput to access it.

ref callback function

The ref attribute can also be a callback function instead of a name. This function will be executed immediately after the component is mounted. The referenced component will be used as a parameter of the function, and the function can use the component parameter immediately or save it for later use.

Its form is also relatively simple:

render: function() {
   return <TextInput ref={(c) => this._input = c} } />;
},
componentDidMount: function() {
   this._input.focus();
},

or

render: function() {
    return (
      <TextInput
        ref={function(input) {
          if (input != null) {
            input.focus();
          }
        }} />
    );
},

It should be noted here that when the reference component is uninstalled and the ref is changed, the parameter value of the previous ref will be null. This will effectively prevent memory leaks. So there will be an if judgment in the above code:

if(input != null){
         input.focus();
}

The above introduces the usage scenarios and methods of ref. Now let's complete the above example to achieve the function of getting focus .

var App = React.createClass({
    getInitialState: function() {
        return {userInput: ''};
    },
    handleChange: function(e) {
        this.setState({userInput: e.target.value});
    },
    clearAndFocusInput: function() {
        this.setState({userInput: ''}); // Clear the input
        // We wish to focus the <input /> now!
        if (this.refs.myTextInput !== null) {
            this.refs.myTextInput.focus();
        }
    },
    render: function() {
        return (
            <div>
                <input
                    value={this.state.userInput}
                    onChange={this.handleChange}
                    ref=”myTextInput”      
                                         />
                <input
                    type="button"
                    value="Reset And Focus"
                    onClick={this.clearAndFocusInput}
                    />
            </div>
        );
    }
});
ReactDOM.render(
    <App />,
    document.getElementById('content')
);

In this example, the render function returns a description of an <input /> instance. But the actual instance is obtained through this.refs. myTextInput. As long as a child component returned by render has ref="myTextInput", this.refs. myTextInput will get the correct instance.

The above is all about ref. For more information about ref, please refer to Ref to Components .

This is all we have to say about ref. I hope this article will be helpful to you.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Determining the referer in PHP

Publish Date:2025/04/13 Views:133 Category:PHP

$_SERVER['HTTP_REFERER'] Provides us with a referrer URL to determine the user request on the server. However, this is not a best practice because the referrer can be HTTP compromised through . $_SESSION[] Determine the referrer in PHP usin

Implementing refresh permissions in MySQL

Publish Date:2025/04/10 Views:118 Category:MySQL

This tutorial explains the refresh permissions operation and its implementation with examples. Implementing refresh permissions in MySQL MySQL implements user management through grant tables to ensure security and access control in the serv

How to fix Git error Error: src refspec master does not match any

Publish Date:2025/04/05 Views:124 Category:Git

When using Git, we may encounter the error "src refspace master does not match any". Here's what the error means and how to fix it. What does src refspec master does not match any Mean in Git mean? We may encounter this error when we try to

Fatal: Refusing to Merge Unrelated Histories error in Git

Publish Date:2025/03/29 Views:124 Category:Git

This article outlines the steps required to resolve the fatal: refusing to merge unrelated histories error in Git. We usually encounter such errors when trying to merge two unrelated Git projects into one branch. It pops up when the receivi

Git refresh remote branch

Publish Date:2025/03/28 Views:94 Category:Git

Git is considered to be the most accurate and the most used software by developers in their projects and can be operated by multiple developers simultaneously. It provides many unique and quirky features to the developers which are very dif

How to avoid cross-origin (CORS) issues in React/Next.js

Publish Date:2025/03/17 Views:170 Category:NETWORK

In this article, we will introduce how to avoid cross-origin (CORS) issues in React/Next.js. Cross-origin resource sharing (CORS) is a protocol that defines how web requests should be handled when crossing different URLs.

React Tutorial - Transferring Props

Publish Date:2025/03/16 Views:188 Category:React

React transfers Props. Props are generated when components are encapsulated. Components expose some properties (Props) to the outside world to complete some functions.

React Tutorial: Props Anti-Pattern

Publish Date:2025/03/16 Views:187 Category:React

React's Props anti-pattern, using Props to generate state in getInitialState is an anti-pattern - Anti-Pattern.

React Tutorial - Props Validation

Publish Date:2025/03/16 Views:102 Category:React

Props validation is a very useful way to use components correctly. It can avoid many bugs and problems as your application becomes more and more complex. In addition, it can make your program more readable.

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial