使用中的React App中的DOM元素焦点效果问题

我想在组件渲染时集中一些html元素。我需要该焦点,以便能够在外部单击时关闭该组件。问题是,当我使用开发人员工具检查实际焦点时,在渲染组件后它就停留在“主体”上。

所以我的想法是明确集中该组件中的某个元素,这是行不通的。

这是我的代码

// 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。它与输入字段一起使用。但是组件本身没有输入字段,当我插入一个类型为“ hidden”的字段时,它不再起作用。

你们能帮我解决这个问题吗?谢谢!

编辑:我只能使用挂钩/功能组件。

mx9903440 回答:使用中的React App中的DOM元素焦点效果问题

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>
    );
}
本文链接:https://www.f2er.com/3160833.html

大家都在问