添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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); }}

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?

I'm assuming <Field /> is a Functional component. And inside <Field /> component there is a input element. If that is the case then you have to use forwardref to pass down ref to child. Here is the reference link

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

the weird thing is that if i console.log(element) inside the function is shows me current:{...lots of pros} – RamAlx Sep 21, 2020 at 16:16 Yes that's the actual behavior of ref right? Ref gives you the whole reference of the element. – reachtokish Sep 21, 2020 at 16:20

I don't know if you found the answer but I had the same issue with a double problem.

  • I was using a class stateless component so no ref and this is why I am assuming you were getting the error (How can I attach to a stateless component's ref in React?)
  • In order to fix this issue you need add a tabIndex in order to set focus in a div (not input element) (Is it possible to focus on a <div> using JavaScript focus() function?)
  • Thanks for contributing an answer to Stack Overflow!

    • Please be sure to answer the question. Provide details and share your research!

    But avoid

    • Asking for help, clarification, or responding to other answers.
    • Making statements based on opinion; back them up with references or personal experience.

    To learn more, see our tips on writing great answers.