¿Es posible pasar la clave/ID a un evento onFocus?
Aquí está mi código:
handleChange: (e: SyntheticEvent<FormInputElements>) => void, handleFocus: (e: SyntheticEvent<FormInputElements>) => void, const handleEvent = (event?: EventListener, inputvalue: string) => { if (event) { return event(component, inputvalue); } return null; }; const handleChange = (e: SyntheticEvent<FormInputElements>) => { handleEvent(onChange, e.currentTarget.value); if (hasFocus && showErrors) { setResolvedErrors(true); handleFocus(component.key); } }; const handleFocus = (e: SyntheticEvent<FormInputElements>) => { setHasFocus(true); handleEvent(onFocus, e.currentTarget.value); }; Básicamente, dentro de mi evento handleChange , si se ejecuta la declaración if, me gustaría ejecutar el evento handleFocus , pero pasarle la clave de mi componente, para que se centre en el elemento correcto.
Puede usar el gancho useRef para ese propósito.
Echa un vistazo al ejemplo dado:
function TextInputWithFocusButton() { const inputEl = useRef(null); const onButtonClick = () => { // `current` points to the mounted text input element inputEl.current.focus(); }; return ( <> <input ref={inputEl} type="text" /> <button onClick={onButtonClick}>Focus the input</button> </> ); }