React - 使用对象或数组在一行中创建多个 useRef

React - Create multiple useRefs in one line using object or array

我想声明多个 useRef 并将它们全部放在 1 个对象或数组中。如果那不可能,那么任何在一行中声明多个引用的方法,比如数组解构

到目前为止我都试过了,都没有用。

尝试 1

const inputRefs = useRef({ input1: null, input2: null, input3: null, input4: null })

function focusInput() {
    inputRefs.input2.current.focus()
}

return (
    <div>
        <input type="text" ref={inputRefs.input1} />
        <input type="text" ref={inputRefs.input2} />
        <input type="text" ref={inputRefs.input3} />
        <input type="text" ref={inputRefs.input4} />
        <button onClick={focusInput}>focus</button>
    </div>
)

尝试 2

const [input1, input2, input3, input4] = Array(4).fill(useRef(null))

function focusInput() {
    input2.current.focus()
}

return (
    <div>
        <input type="text" ref={input1} />
        <input type="text" ref={input2} />
        <input type="text" ref={input3} />
        <input type="text" ref={input4} />
        <button onClick={focusInput}>focus</button>
    </div>
)

注意我在示例中只有 4 个输入,但实际上我有更多,因此我想找到一种方法。谢谢

需要纠正的地方很少。

  1. useRef 是一个反应钩子(应该在函数的顶层定义)。因此,要创建引用并将它们存储在数组中,您应该使用 createRef.
  2. Array.fill does not create 4 new refs instead of that share a single ref. That's why even though you clicked on the button always last input is always referred to. To get rid of that, use Array.from 如下所示。
import { createRef } from "react";

export default function App() {
  const [input1, input2, input3, input4] = Array.from({ length: 4 }, () =>
    createRef(null)
  );

  function focusInput() {
    input2.current.focus();
  }

  return (
    <div>
      <input type="text" ref={input1} />
      <input type="text" ref={input2} />
      <input type="text" ref={input3} />
      <input type="text" ref={input4} />
      <button onClick={focusInput}>focus</button>
    </div>
  );
}

您可以在输入包装器上设置 ref 并通过 DOM API.

处理输入
const containerRef = useRef(null);

function focusInput() {
    const containerNode = containerRef.current;
    containerNode.childNodes[2].focus();
}

return (
    <div ref={containerRef}>
        <input type="text" />
        <input type="text" />
        <input type="text" />
        <input type="text" />
        <button onClick={focusInput}>focus</button>
    </div>
)

kk 我找到了与我的第一个类似的方法,但它有效。也欢迎进一步的建议

import { useRef } from "react";

export default function App() {
  const inputRefs = {input1: useRef(null), input2: useRef(null), input3: useRef(null), input4: useRef(null)}

  function focusInput() {
    inputRefs.input2.current.focus();
  }

  return (
    <div>
      <input type="text" ref={inputRefs.input1} />
      <input type="text" ref={inputRefs.input2} />
      <input type="text" ref={inputRefs.input3} />
      <input type="text" ref={inputRefs.input4} />
      <button onClick={focusInput}>focus</button>
    </div>
  );
}