【问题标题】:Focus DOM Element in React App in useEffect ProblemReact App中的焦点DOM元素在useEffect问题中
【发布时间】:2020-03-01 15:29:50
【问题描述】:

我想在组件呈现时聚焦一些 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();

附言。它适用于输入字段。但是组件本身没有输入字段,当我插入一个 type="hidden" 时,它不再起作用了。

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

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

【问题讨论】:

    标签: html reactjs dom focus


    【解决方案1】:

    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>
        );
    }
    

    【讨论】:

    • 谢谢!对于未来的读者,该提示解决了我的问题:在 React 中,我必须像这样“tabIndex={-1}” 来实现它
    猜你喜欢
    • 2016-10-12
    • 2017-12-22
    • 2021-09-20
    • 2021-02-17
    • 2021-09-08
    • 1970-01-01
    • 2018-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多