![](/img/trans.png)
[英]Cannot apply current.focus() to button using useRef() in React Native
[英]Using React useRef() to apply focus to a TextArea inside a Popover when opened
我有一个包含 TextArea 的 AntDesign Popover。
<Popover trigger="click" content={footnoteContent} title="Footnote" visible={footnotePopoverVisible} onVisibleChange={handleFootnoteVisibleChange} >
... a custom Button...
</Popover>
用于内容的const如下:
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>
);
我知道这里发生了很多事情。 但是,请注意,我已将 autoFocus 设置为开启,并且正如预期的那样,当我第一次打开 Popover 时,TextArea 实际上确实获得了焦点。 但是,任何后续点击打开同一个 Popover 和 TextArea 都不再自动获得焦点。 我调查并发现useRef()
钩子应该有帮助。
因此,在我的功能组件顶部附近,我声明了:
const inputRef = useRef();
请注意,在我的 TextArea 中,我已将 ref 设置如下(按照我在网上找到的一些示例):
ref={ref => { inputRef.current = ref; }}
上面的弹出onVisibleChange
代码调用了一个指向这个函数的onVisibleChange
函数:
function handleFootnoteVisibleChange (visible) {
setFootnotePopoverVisible(visible);
if (visible) {
if (inputRef.current) {
console.log(inputRef.current);
inputRef.current.focus();
}
}
}
我希望在弹出窗口可见时重新聚焦文本区域。 然而,似乎什么也没有发生。 当我检查会话并检查console.log(inputRef.current);
上面,似乎有一个focus()
函数要调用……但什么也没发生。
使用useRef
,将 ref 直接应用于您的输入字段。
const myRef = useRef();
...
<MyInput ref={myRef} ...
您展示的方法是来自基于类的组件的遗留ref
分配。 useRef
工作方式不同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.