0

您好,我想在页面加载时自动聚焦输入。我必须使用 Suspense,因为我使用的是 i18n。我有自动对焦代码,但效果不佳。

<Suspense fallback={<LoadingScreen/>}>
  <Input />
</Suspense>
const Input = () => {
  const inputRef = useRef(null);
  useEffect(() => {
    inputRef.current.focus();
  }, []);
  return (
    <input ref={inputRef} type="text"/>
  );
};

当我消除悬念时,我的代码运行良好。但我需要 i18n 的悬念。我怎样才能解决这个问题?

4

1 回答 1

0

Thy using useCallback instead of useEffect.

const Input = () => {
  const callbackRef = useCallback(ref => ref && ref.focus());
  return (
    <input ref={callbackRef} type="text"/>
  );
};

It didn't work because useEffect was called when the component is Mounted which is happens before the <Suspese /> is completed.

于 2021-12-08T21:52:47.890 回答