【发布时间】:2021-05-27 21:12:50
【问题描述】:
我一直在寻找一种在 React 代码中正确聚焦和选择复选框的方法。
我在下面的示例中使用的方法 focus() 和 select() 不起作用:
import React, { useRef } from "react";
export const HelloWorld = () => {
const checkboxref = useRef(null);
const handleOnClick = () => {
checkboxref.current.focus();
checkboxref.current.select();
};
return (
<div>
<button onClick={handleOnClick}>Focus</button>
<input type="checkbox" ref={checkboxref} />
</div>
);
};
当我点击按钮时,我的复选框没有聚焦,也没有被选中...
请问有什么解决办法吗?
非常感谢。
【问题讨论】:
-
您单击一个按钮,我敢打赌,在您释放鼠标按钮后该按钮具有焦点。尝试启动一个计时器,看看它是否有效