Today write page (react project), to implement an input box, and then with the clear button. After clearing, focus the cursor inside the input.

I’m currently using the React 17.0.2 version, which uses functional components. Previously in the class component, we could write:

xxx.jsx constructor(props) { super(props); This.inputel = react.createref (); // Create a ref with react.createref () and mount it to the component. } <input ref={inputEl}></input>Copy the code

We can then retrieve the input field with this. InputEl, blablabla~

Functional component

const inputEl = useRef(null);

 <input ref={inputEl} id='inputAmount' value={inputVal} onChange={handleInputChange}/>
 
Copy the code

Then, you can get the input field through inputEl

Inputel.focus () // Get focusCopy the code

Or, instead of using the React API, use the native-access method, for example:

document.querySelector('#inputAmount'); / / can also be usedCopy the code