几乎所有关于设置焦点的文章和示例都使用输入元素进行了解释。它适用于输入元素,但如何使用 React useRef 和 useEffect 挂钩将焦点设置到 div 元素?
如何使用toHaveFocus
react -testing-library 对其进行测试?
几乎所有关于设置焦点的文章和示例都使用输入元素进行了解释。它适用于输入元素,但如何使用 React useRef 和 useEffect 挂钩将焦点设置到 div 元素?
如何使用toHaveFocus
react -testing-library 对其进行测试?
在搜索了一段时间并浪费了相当多的时间之后,我能够做到。在这里分享给朋友!!
组件文件 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>
);
}
测试文件 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();
});
如果您使用样式化的 div 而不是普通的 html div,则使用innerRef
而不是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:别忘了tabIndex