react input Сохранение позиции курсора в input (напр. при применении маски)
Primary tabs
Пример на typescript (для чистого js смысл такой же, только без типов):
import React from "react"; export type CursorPositionSaverPropsType = any; export default function CursorPositionSaver(props: CursorPositionSaverPropsType) { const [shownValue, setShownValue] = React.useState(''); const [position, setPosition] = React.useState(0); const inputRef: any = React.useRef<HTMLInputElement>(null); // применяем простую маску, при которой курсор прыгает в конец const handleChange = React.useCallback((evt) => { let value = evt.target.value.replace(/_/g, ''); let newValue = (value.length <= 10) ? value + '_'.repeat(10 - value.length) : value; setShownValue(newValue); setPosition(evt.target.selectionStart); }, []); React.useEffect(() => { if (inputRef !== null) { // возвращаем курсор на оригинальную позицию inputRef.current.selectionStart = position; inputRef.current.selectionEnd = position; console.log('position', position); } }, [position]); console.log('inputRef.current', inputRef.current); return ( <> <div> <input value={shownValue} onChange={handleChange} ref={inputRef} /> </div> </> ); }
- Log in to post comments
- 3039 reads