【问题标题】:call useRef inside a useEffect got Invalid hook call error在 useEffect 中调用 useRef 得到 Invalid hook call 错误
【发布时间】:2020-09-08 12:06:12
【问题描述】:

如何为尚不存在的元素创建 ref?

我有一个动态表单,如何为每个输入创建 ref?表单有一个添加新输入选项,所以每次用户点击添加新输入时我都必须动态创建一个新的引用?

执行此操作时出错,无法正常工作:

  useEffect(() => {
    const inputRef = useMemo(() => Array(totalInput).fill(0).map(i => useRef()), []);
  }, [createdInput])

但如果我这样做

const inputRef = useMemo(() => Array(totalInput).fill(0).map(i => useRef()), []);
console.log(inputRef)

inputRef 在数组中只有一项。

【问题讨论】:

    标签: reactjs react-hooks


    【解决方案1】:

    如果输入是动态的,而不是为每个输入使用一个 ref,您可以考虑使用 DOM 方法,并为父级使用单个 ref。例如:

    return (
      <div ref={containerRef}>
        {inputDatas.map(inputData => <Input inputData={inputData} />)}
      </div>
    );
    

    然后选择nth 输入,使用:

    containerRef.current.children[n]
    

    要使用的选择方法取决于您的输入结构。你可能想要containerRef.current.querySelectorAll('input')[n] 之类的东西。

    【讨论】:

    • 不建议,我有多种输入和来自第三方的其他组件,最好在每种输入上使用 ref
    • 然后检查 HTML 结构以确定您需要哪种选择器来仅选择您感兴趣的输入。例如,querySelectorAll('input:nth-child(2)') 将选择第二个孩子 &lt;input&gt;s它的父母。或者,'span + input' 选择紧跟在&lt;span&gt; 之后的&lt;input&gt;s。 CSS 选择器非常灵活和简洁。
    猜你喜欢
    • 1970-01-01
    • 2019-10-08
    • 1970-01-01
    • 1970-01-01
    • 2019-11-19
    • 2022-06-29
    • 2023-02-08
    • 2021-03-20
    • 2021-06-04
    相关资源
    最近更新 更多