问题
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