【发布时间】:2022-01-15 17:10:14
【问题描述】:
我已经为我的 React 组件编写了几个测试,当我排除以下代码时它们都可以工作:
useEffect(() => {
if (lastClickedElement) {
const findElement = document.getElementById(lastClickedElement);
findElement.focus();
} else {
const findFirstLink = document.querySelectorAll("a");
findFirstLink[0].focus();
}
但是,当我包含它时,我收到错误:“无法读取未定义的属性'焦点'”。 谁能解释为什么我的测试在没有它的情况下可以工作,然后在包含它时导致此错误?
我尝试使用 if 语句,如果 findFirstLink 等于“null”则不返回任何内容,但随后我收到此错误“Uncaught TypeError: Cannot read property 'focus' of null throwed”。
代码如下所示:
{data.items.map((item, i) => {
return (
<div>
<a href={item.id}>{item.label}</a>
</div>
)
}
)}
【问题讨论】:
-
可能是半相关的问题,为什么使用
document.getElementById而不是将ref传递给相关元素并使用ref.current.focus()?
标签: reactjs react-hooks karma-runner enzyme