Popover 内的 Ref null

IT技术 reactjs material-ui popover react-ref
2021-04-29 15:06:39

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

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

任何帮助深表感谢。

3个回答

无需为此使用 ref,只需将 autoFocus 添加到您的输入中:

<input autoFocus placeholder="search" />

由于您控制了open异步via 状态,因此当inputRef尝试获取元素时,状态尚未更新,并且Proper尚未创建子项。

您可以向 中添加 async/awaitsetState以使其正常工作。

const handleClick = async event => {
  await setAnchorEl(event.currentTarget);
  inputRef.current.focus();
};

编辑 heuristic-allen-hubry

在此处输入图片说明

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

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

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

通过超时,您可以确保安装弹出框并且输入可见,因此在超时过后输入将被聚焦。使用 async/await 更适用于 promise。