Uncaught Invariant Violation:函数组件不能有引用。你的意思是使用 React.forwardRef() 吗?

时间:2021-05-27 11:46:32

标签: javascript reactjs

当我的内容被加载但出现问题时,我需要 ref 来聚焦。请告诉我这段代码有什么问题。对于功能组件

const Boost = useRef(null);
  useEffect(() => {
    Boost.current.focus();
  });
return (
      <h1 id="keepYourPlan" ref="Boost" tabIndex="-1">
        Milan
      </h1>
);

1 个答案:

答案 0 :(得分:0)

useEffect 不是确定组件是否已加载的理想方式。您的 ref 可能为空,而且您的副作用将在每次渲染时运行。我建议改用 ref 回调:

const focusOnMount = (node) => node?.focus();

return (
      <h1 id="keepYourPlan" ref={focusOnMount} tabIndex="-1">
        Milan
      </h1>
);

您可以在此处阅读有关回调引用的更多信息: https://reactjs.org/docs/refs-and-the-dom.html

如果您将 ref 或 refCallback 传递给您自己的自定义组件而不是此处的 h1,则如果自定义组件是功能组件,则需要将其包装在 forwardRef 中。有关参考转发的更多信息,请访问:https://reactjs.org/docs/forwarding-refs.html