how react programmatically focus input

前端 未结 6 2085
滥情空心
滥情空心 2020-12-15 03:01

I\'m trying to implement a very simple use case, a UI feature, where:

  1. There is a label with some content in it
  2. If clicked, a text input replaces it wi
6条回答
  •  旧巷少年郎
    2020-12-15 03:33

    @BenCarp's answer in typescript

    Pass the inputRef to an input and just call setFocus to set the focus to it.

    export const useInputFocus = (): [MutableRefObject, () => void] => {
      const inputRef = useRef();
      const setFocus = (): void => {
        const currentEl = inputRef.current;
        if (currentEl) {
          currentEl.focus();
        }
      };
      return [inputRef, setFocus];
    };
    

提交回复
热议问题