Focus DOM Element in React App in useEffect 问题
Focus DOM Element in React App in useEffect Problem
我想在组件呈现时聚焦一些 html 元素。我需要那个焦点,这样我才能在外部点击时关闭组件。问题是,当我使用开发人员工具检查实际焦点时,它在组件呈现后保持在 'body' 上。
所以我的想法是明确关注该组件中的一个元素,但这行不通..
这是我的代码
// initiale the useRef
const initialFocusRef = useRef(null);
// connecting the ref to the div element
<div className="edi-frame" ref={initialFocusRef}>
// in useEffect i try to focus the element
initialFocusRef.current.focus();
Ps。它适用于输入字段。但是组件本身没有输入字段,当我插入一个带有 type="hidden" 的字段时,它不再工作了。
你们能帮我解决这个问题吗?谢谢!
编辑:我只能使用挂钩/功能组件。
div
- 不是可聚焦元素,但您可以通过添加使其可聚焦
属性 tabindex
:
<div className="edi-frame" tabindex="-1" ref={initialFocusRef}>
如果您想通过在组件外部单击来关闭组件,我建议您使用 react-onclickoutside
:
function ModalComponent({ close }) {
const ref = useRef(null)
useOnClickOutside(ref, close)
return (
<div className="edi-frame" ref={ref}>Some content</div>
);
}
我想在组件呈现时聚焦一些 html 元素。我需要那个焦点,这样我才能在外部点击时关闭组件。问题是,当我使用开发人员工具检查实际焦点时,它在组件呈现后保持在 'body' 上。
所以我的想法是明确关注该组件中的一个元素,但这行不通..
这是我的代码
// initiale the useRef
const initialFocusRef = useRef(null);
// connecting the ref to the div element
<div className="edi-frame" ref={initialFocusRef}>
// in useEffect i try to focus the element
initialFocusRef.current.focus();
Ps。它适用于输入字段。但是组件本身没有输入字段,当我插入一个带有 type="hidden" 的字段时,它不再工作了。
你们能帮我解决这个问题吗?谢谢!
编辑:我只能使用挂钩/功能组件。
div
- 不是可聚焦元素,但您可以通过添加使其可聚焦
属性 tabindex
:
<div className="edi-frame" tabindex="-1" ref={initialFocusRef}>
如果您想通过在组件外部单击来关闭组件,我建议您使用 react-onclickoutside
:
function ModalComponent({ close }) {
const ref = useRef(null)
useOnClickOutside(ref, close)
return (
<div className="edi-frame" ref={ref}>Some content</div>
);
}