如何使用 useEffect 和 useRef 钩子将焦点设置到反应组件中的 div 元素?以及如何测试它? [英] How to set focus to a div element in a react component using useEffect and useRef hooks? And how to test it?
问题描述
几乎所有关于设置焦点的文章和示例都使用 input 元素进行解释.它适用于输入元素,但如何使用 React useRef 和 useEffect 钩子将焦点设置到 div 元素?
如何使用react-testing-library的toHaveFocus
进行测试?
找了一阵子,浪费了不少时间,终于搞定了.在这里分享给朋友们!!
组件文件 SetFocusToDivComponent.js
import React, { useRef, useEffect } from 'react';导出默认函数 SetFocusToDivComponent() {const containerRef = useRef(null);useEffect(() => {containerRef.current.focus();});返回 ();}
测试文件 SetFocusToDivComponent.tests.js
从'react'导入React;从 'react-dom' 导入 ReactDOM;从'react-dom/test-utils'导入{行为};从 './SetFocusToDivComponent' 导入 SetFocusToDivComponent;让容器;beforeEach(() => {container = document.createElement('div');document.body.appendChild(container);});afterEach(() => {document.body.removeChild(容器);容器 = 空;});test('设置焦点', () => {行为(() => {ReactDOM.render( , 容器);});expect(container.querySelector('div[data-test="container"]')).toHaveFocus();});
如果您使用样式化 div 而不是纯 html div,则使用 innerRef
而不是 ref
const StyledDiv = styled.div`边界半径:0 0 5px 5px;边框:1px纯绿色;`;<StyledDiv数据测试={'容器'}innerRef={errorDisplayWrapperRef}tabIndex={-1}>你好呀!!</StyledDiv>
PS:不要忘记tabIndex
All most all the articles and examples about setting focus are explained using input element. It works well with input element but how to set focus to a div element using React useRef and useEffect hooks?
How to test it using toHaveFocus
of react-testing-library?
解决方案 After searching for a while and wasting quite a bit of time, I was able to do it. Sharing it here for friends!!
Component file SetFocusToDivComponent.js
import React, { useRef, useEffect } from 'react';
export default function SetFocusToDivComponent() {
const containerRef = useRef(null);
useEffect(() => {
containerRef.current.focus();
});
return (
<div
data-test={'container'}
ref={errorDisplayWrapperRef}
tabIndex={-1}
>
Hello There!!
</div>
);
}
Test file SetFocusToDivComponent.tests.js
import React from 'react';
import ReactDOM from 'react-dom';
import { act } from 'react-dom/test-utils';
import SetFocusToDivComponent from './SetFocusToDivComponent';
let container;
beforeEach(() => {
container = document.createElement('div');
document.body.appendChild(container);
});
afterEach(() => {
document.body.removeChild(container);
container = null;
});
test('setting focus', () => {
act(() => {
ReactDOM.render(<SetFocusToDivComponent />, container);
});
expect(container.querySelector('div[data-test="container"]')).toHaveFocus();
});
If you are using a styled div instead of plain html div, then use innerRef
instead of ref
const StyledDiv = styled.div`
border-radius: 0 0 5px 5px;
border: 1px solid green;
`;
<StyledDiv
data-test={'container'}
innerRef={errorDisplayWrapperRef}
tabIndex={-1}
>
Hello There!!
</StyledDiv>
PS: Don't forget tabIndex
这篇关于如何使用 useEffect 和 useRef 钩子将焦点设置到反应组件中的 div 元素?以及如何测试它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文