我正在尝试在打开弹出窗口时自动聚焦输入元素。这是它的沙箱:https : //codesandbox.io/s/green-bash-x6bj4?file=/ src/ App.js
这里的问题是当前属性在 ref 上始终为 null。这是 forwardRef 可能有帮助的情况吗?我对它不是很了解,所以发布它。
任何帮助深表感谢。
我正在尝试在打开弹出窗口时自动聚焦输入元素。这是它的沙箱:https : //codesandbox.io/s/green-bash-x6bj4?file=/ src/ App.js
这里的问题是当前属性在 ref 上始终为 null。这是 forwardRef 可能有帮助的情况吗?我对它不是很了解,所以发布它。
任何帮助深表感谢。
无需为此使用 ref,只需将 autoFocus 添加到您的输入中:
<input autoFocus placeholder="search" />
您可以简单地在 setState 之后添加一个回调,如下所示:
this.setState(
{
anchorEl: e.currentTarget,
isPopoverOpen: true,
},
() => {
setTimeout(() => {
if (this.inputRef.current) {
return this.inputRef.current.focus();
}
return null;
}, 200);
}
);
};
通过超时,您可以确保安装弹出框并且输入可见,因此在超时过后输入将被聚焦。使用 async/await 更适用于 promise。