admin管理员组

文章数量:1312862

I am new in the React world and was learning about Refs. The React doc says that:

Refs provide a way to access DOM nodes or React elements created in the render method.

I think that we can do the same thing with the querySelector function.
The React doc gives an example of how can we use Refs to focus on the input element.
Here's the code ->

class CustomTextInput extends React.Component {
  constructor(props) {
    super(props);
    // create a ref to store the textInput DOM element
    this.textInput = React.createRef();
    this.focusTextInput = this.focusTextInput.bind(this);
  }

  focusTextInput() {
    // Explicitly focus the text input using the raw DOM API
    // Note: we're accessing "current" to get the DOM node
    this.textInput.current.focus();
  }

  render() {
    // tell React that we want to associate the <input> ref
    // with the `textInput` that we created in the constructor
    return (
      <div>
        <input
          type="text"
          ref={this.textInput} />
        <input
          type="button"
          value="Focus the text input"
          onClick={this.focusTextInput}
        />
      </div>
    );
  }
}
<script src=".6.3/umd/react.production.min.js"></script>
<script src=".6.3/umd/react-dom.production.min.js"></script>

I am new in the React world and was learning about Refs. The React doc says that:

Refs provide a way to access DOM nodes or React elements created in the render method.

I think that we can do the same thing with the querySelector function.
The React doc gives an example of how can we use Refs to focus on the input element.
Here's the code ->

class CustomTextInput extends React.Component {
  constructor(props) {
    super(props);
    // create a ref to store the textInput DOM element
    this.textInput = React.createRef();
    this.focusTextInput = this.focusTextInput.bind(this);
  }

  focusTextInput() {
    // Explicitly focus the text input using the raw DOM API
    // Note: we're accessing "current" to get the DOM node
    this.textInput.current.focus();
  }

  render() {
    // tell React that we want to associate the <input> ref
    // with the `textInput` that we created in the constructor
    return (
      <div>
        <input
          type="text"
          ref={this.textInput} />
        <input
          type="button"
          value="Focus the text input"
          onClick={this.focusTextInput}
        />
      </div>
    );
  }
}
<script src="https://cdnjs.cloudflare./ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Doing the same thing with querySelector ->

class CustomTextInput extends React.Component {
constructor(props) {
    super(props);
    this.textInput = React.createRef();
  }

  focusTextInput = () => {
    const input = document.querySelector("input");
    input.focus();
  };

  render() {
    return (
      <div>
        <input type="text" ref={this.textInput} />
        <button type="button" onClick={this.focusTextInput}>
          Focus the Text Input
        </button>
      </div>
    );
  }
}
<script src="https://cdnjs.cloudflare./ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Share Improve this question edited Jun 15, 2020 at 1:11 Boann 50.1k16 gold badges124 silver badges152 bronze badges asked Jun 14, 2020 at 18:22 Yogesh TripathiYogesh Tripathi 7356 silver badges16 bronze badges 17
  • 2 Suppose there's more than one input in the document. How do you know your querySelector returns the correct one? What if your ponent is used more than once in the same view? – ray Commented Jun 14, 2020 at 18:24
  • 1 @rayhatfield we can add id to the input – Yogesh Tripathi Commented Jun 14, 2020 at 18:25
  • 2 Important NOTE: .querySelector --> returns the first Element within the document that matches the specified selector, or group of selectors. .querySelectorAll() --> returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors. – dale landry Commented Jun 14, 2020 at 18:25
  • 2 querySelector() search among all html elements to find the target element but by using ref you have access directly to the element. additionally, the element that you are looking for may change, for example its cssClass may be removed and you won't be able to find it anymore. – Ehsan Nazeri Commented Jun 14, 2020 at 18:41
  • 3 Over simplification of reason is that React replaces existing elements in dom as state changes and although they look the same and have same properties they are not the exact same element object each time. React does this under the hood and what you should focus on is the state and not the dom – charlietfl Commented Jun 14, 2020 at 18:41
 |  Show 12 more ments

2 Answers 2

Reset to default 2

Since, the framework itself has exposed a method to do something which can be done through vanilla javascript, it certainly has added advantages. One of the scenario I can think of is using React.forwardRef which can be used for:

  • Forwarding refs to DOM ponents
  • Forwarding refs in higher-order-ponents

As explained in the React docs itself:

const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref} className="FancyButton">
    {props.children}
  </button>
));

// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;

you don't need react or angular to do any web development, angular and react give us a wrapper which will try to give us optimize reusable ponent, all the ponent we are developing using react can be done by web-ponent but older browser don't support this.

i am listing some of benefit of using ref in React

  1. this will be helpful for if you are using server side rendering, Be careful when you use Web API(s) since they won’t work on server-side Ex, document, Window, localStorage
  2. you can easily listen to changes in state of object, you don't have to maintain or query the DOM again and again and the framework will do this for you.

本文标签: javascriptWhy use Ref when we can use querySelectorStack Overflow