React 中解决 Function components cannot have string refs 错误

当我们在函数组件中使用字符串作为引用时,会出现错误“Function components cannot have string refs”。 要解决该错误,需要使用 useRef() 钩子来获取一个可变的 ref 对象,我们可以将其用作组件内部的 ref。

下面是错误发生方式的示例。

export default function App() {
  // 在严格模式树中找到了字符串 ref。
  // Function components cannot have string refs.
  // 我们建议改用 useRef()。
  return (
    <div>
      <input type="text" id="message" ref="msg" />
    </div>
  );
}

代码片段中的问题是我们使用字符串作为引用。

要解决该错误,改用 useRef 钩子来获取可变 ref 对象。

import {useEffect, useRef} from 'react';

export default function App() {
  const refContainer = useRef(null);

  useEffect(() => {
    // 这是对输入元素的引用
    console.log(refContainer.current);

    refContainer.current.focus();
  }, []);

  return (
    <div>
      <input type="text" id="message" ref={refContainer} />
    </div>
  );
}

useRef() 钩子可以传递一个初始值作为参数。 该钩子返回一个可变的 ref 对象,其 .current 属性被初始化为传递的参数。

注意 ,我们必须访问 ref 对象的 current 属性才能访问我们设置 ref 属性的输入元素。

当我们传递像 <input ref={myRef} /> 这样的 ref 对象时,React 会将 ref 对象的 .current 属性设置为对应的 DOM 节点。

useRef 钩子创建一个普通的 JavaScript 对象,但在每次渲染时为我们提供相同的 ref 对象。 换句话说,它几乎是一个带有 .current 属性的记忆对象值。

需要注意的是,当更改 ref 的当前属性的值时,不会导致重新渲染。

例如,引用不必包含在 useEffect 钩子的依赖项数组中,因为更改它的当前属性不会导致重新渲染。

import {useEffect, useRef} from 'react';

export default function App() {
  const refContainer = useRef(null);

  const refCounter = useRef(0);

  useEffect(() => {
    // ?️ 这是对输入元素的引用
    console.log(refContainer.current);
    refContainer.current.focus();

    // ?️ 增加 ref 值不会导致重新渲染
    refCounter.current += 1;
    console.log(refCounter.current);
  }, []);


  return (
    <div>
      <input type="text" id="message" ref={refContainer} />
    </div>
  );
}

示例中的 useEffect 钩子只运行了 2 次,因为 useRef 在其内容更改时不会通知我们。

更改对象的当前属性不会导致重新渲染。