在Popover中引用NULL [英] Ref null inside Popover

查看:65
本文介绍了在Popover中引用NULL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将输入元素自动聚焦在弹出窗口的打开上.这是它的沙箱: https://codesandbox.io/s/green-bash-x6bj4?file =/src/App.js

I am trying to autofocus an input element on opening of a popover. Here is the sandbox for it: https://codesandbox.io/s/green-bash-x6bj4?file=/src/App.js

这里的问题是,当前属性在ref上始终为null.这是 forwardRef 可能有帮助的情况吗?我不太了解它,所以发布它.

Issue here is that the current property is always null on ref. Is this a case where forwardRef might help? I am not much aware of it so posting it.

非常感谢您的帮助.

推荐答案

您可以简单地在setState之后添加回调,如下所示:

You could simple add a callback after the setState, like this:

    this.setState(
      {
        anchorEl: e.currentTarget,
        isPopoverOpen: true,
      },
      () => {
        setTimeout(() => {
          if (this.inputRef.current) {
            return this.inputRef.current.focus();
          }

          return null;
        }, 200);
      }
    );
  };

使用超时,您可以确保已安装弹出窗口并且输入可见,因此在超时后输入将被聚焦.使用async/await的目的更多.

With the timeout you can secure that the popover is mounted and the input is visible, so the input will be focused when the timeout is passed. Using async/await is more for promises.

这篇关于在Popover中引用NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆