How to set focus in react: 1. Use DOM elements in componentDidMount; 2. Call the DOM API of "this.input.focus()" to automatically focus on the input when the page is loaded. box function.
The operating environment of this tutorial: Windows 10 system, react18.0.0 version, Dell G3 computer.
How to set focus in react?
React automatically focuses on an input box after entering the page
In React.js, you basically don’t need to deal with the DOM directly. React.js provides a series of on* methods to help us monitor events, so there is no need to directly call the DOM API of addEventListener in React.js; in the past, we updated the page through manual DOM operations (for example, with the help of jQuery), but in React. In js, components can be re-rendered directly through setState. When rendering, new props can be passed to sub-components to achieve the page update effect.
The re-rendering mechanism of React.js helps us avoid most DOM update operations, and also allows third-party libraries like jQuery, which mainly encapsulate DOM operations, to be used as our development tools. Removed from the chain.
But React.js cannot fully meet all DOM operation needs. Sometimes we still need to deal with DOM. For example, if you want to automatically focus on an input box after entering the page, you need to call the DOM API of input.focus(). For example, if you want to dynamically obtain the size of a DOM element for subsequent animation, etc.
React.js provides the ref attribute to help us get the DOM node of the mounted element. You can add the ref attribute to a JSX element.
You can see that we added a ref attribute to the input element, and the value of this attribute is a function. When the input element is mounted on the page, React.js will call this function and pass the mounted DOM node to this function. In the function, we set this DOM element as an attribute of the component instance, so that we can get this DOM element through this.input in the future.
Then we can use this DOM element in componentDidMount and call the DOM API of this.input.focus(). Overall, it achieves the function of automatically focusing on the input box after the page is loaded (you can notice that we use the componentDidMount component life cycle).
We can add ref to any HTML element tag to obtain its DOM element and then call the DOM API. But remember one principle: don’t use ref if you can. In particular, avoid using ref for automatic page update operations and event monitoring that React.js can help you do. Redundant DOM operations are actually "noise" in the code, which is not conducive to our understanding and maintenance.
Another way of writing:
Recommended learning: "react video tutorial"
The above is the detailed content of How to set focus in react. For more information, please follow other related articles on the PHP Chinese website!