Ref null inside Popover

眉间皱痕 提交于 2020-07-10 08:49:25

问题


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

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.

Any help is much appreciated.


回答1:


No need to use a ref for that, just add autoFocus to your input:

<input autoFocus placeholder="search" />



回答2:


Since you control the open via state, which is async, when the inputRef tries to get the element, the state hasn't been updated, and the Proper children haven't been created.

You can add an async/await to the setState to make it works.

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




回答3:


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);
      }
    );
  };

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.



来源:https://stackoverflow.com/questions/61098820/ref-null-inside-popover

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!