ref.current.focus() is not a function

use*_*203 6 javascript focus refs reactjs

im trying to use a ref for focusing on the element when onBlur. I'm using react v.16.9.0 My code is this:

const handleKeyDown = (e, element, index) => {
  element.current.focus();
  event.preventDefault();
};

const pinDigitBuilder = () => {
  const arr = Array(...Array(TOTAL_PIN_DIGITS));
  return arr.map((x, i) => {
    const inputRef = useRef(null);
    console.log(inputRef);
    return (
      <Field
        key={`${PIN_DIGIT}${i + 1}`}
        id={`${PIN_DIGIT}${i + 1}`}
        name={`${PIN_DIGIT}${i + 1}`}
        ref={inputRef}
        component={InputTextField}
        className="text xxs2"
        classNameInvalid="text xxs2 error"
        type="text"
        divClassName="fieldWrap"
        maxLength={1}
        normalize={keepNumbersOnly}
        errorStyle={{ display: 'none' }}
        autoComplete="off"
        onBlur={(e) => { handleKeyDown(e, inputRef, i); }}
      />
    );
  });
};
Run Code Online (Sandbox Code Playgroud)

When i click outside the field an error occured saying that element.current.focus();. I dont get it. I use useRef as explained with details in the docs and i dont know what im missing. Any ideas?

小智 4

我假设<Field />是一个功能组件。组件内部<Field />有一个输入元素。如果是这种情况,那么您必须使用forwardref将 ref 传递给子级。这是参考链接

https://reactjs.org/docs/forwarding-refs.html

  • React充满了陷阱 (2认同)