PL
React - jak ustawić kurosr na elemencie input po renderowaniu
0 points
W tym artykule chcielibyśmy pokazać, jak w Reakcie ustawić kursor na elemencie input
bezpośrednio po wyrenderowaniu komponentu.
W poniższym przykładzie używamy dwóch hooków:
useRef
który przechowuje referencję do elementuinput
,useEffect
- metoda.focus()
jest wywoływana, gdy komponentApp
zostanie wyrenderowany.
Uruchamialny przykład:
xxxxxxxxxx
1
// Uwaga: Odkomentuj poniższe linijki podczas pracy z kompilatorem JSX:
2
// import React from 'react';
3
4
const App = () => {
5
const inputRef = React.useRef();
6
React.useEffect(() => {
7
if (inputRef.current) {
8
inputRef.current.focus();
9
}
10
}, []);
11
return (
12
<div>
13
<label>Search: </label>
14
<input ref={inputRef} />
15
</div>
16
);
17
}
18
19
const root = document.querySelector('#root');
20
ReactDOM.render(<App />, root );