I have an AntDesign Popover that contains a TextArea.
<Popover trigger="click" content={footnoteContent} title="Footnote" visible={footnotePopoverVisible} onVisibleChange={handleFootnoteVisibleChange} >
... a custom Button...
</Popover>
The const used for the content is as follows:
const footnoteContent = (
<Form form={form}>
<Form.Item name={`${cellData.key}-fn`} initialValue={initialValue}>
<Tooltip placement="left" title="Press Ctrl + Enter to close this window.">
<Input.TextArea
disabled={disabled}
bordered={false}
autoComplete="off"
style={{ width: "300px" }}
autoSize={{ minRows: 4 }}
placeholder="Enter footnote"
onBlur={() => save(cellData.key, form.getFieldValue(`${cellData.key}-fn`))}
onKeyDown={handleKeyDown}
autoFocus={true}
ref={ref => { inputRef.current = ref; }}
/>
</Tooltip>
</Form.Item>
</Form>
);
I understand there is a lot going on here. However, note that I have set autoFocus on, and as expected, the first time I open the Popover the TextArea does in fact get focus. However, any subsequent clicks to open that same Popover and the TextArea is no longer automatically getting focus. I investigated and discovered useRef()
hooks should help.
So, near the top of my Functional Component I have declared:
const inputRef = useRef();
and note that within my TextArea I have set the ref as follows (following some examples I found online):
ref={ref => { inputRef.current = ref; }}
The popover code above has a call to a function onVisibleChange
which points to this function:
function handleFootnoteVisibleChange (visible) {
setFootnotePopoverVisible(visible);
if (visible) {
if (inputRef.current) {
console.log(inputRef.current);
inputRef.current.focus();
}
}
}
Which I hoped would just re-focus the text area when the popover is made visible. However, nothing seems to happen. When I inspect the session and check the console.log(inputRef.current);
above, there seems to be a focus()
function to call... yet nothing is happening.
With useRef
, apply the ref direct to your input field.
const myRef = useRef();
...
<MyInput ref={myRef} ...
The method you showed is legacy ref
assignment from class based components. useRef
works different.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.