我一直在寻找一种方法来正确地focus和selectReact代码中的复选框。 我在下面的示例中使用的方法
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>
);
};
当我单击按钮时,我的复选框未聚焦且未选中...
请问有什么解决办法吗?
非常感谢。
您不需要创建单独的函数来处理 onChange 事件
const checkboxref = useRef(null);
您可以简单地获取复选框的当前值:
checkboxref.current.checked
// which returns a boolean
使用这个可能会对你有所帮助。在这里,我使用 createRef 而不是 useRef,并且还使用回调挂钩,确保单击按钮时 ref 的可用性。
import React,{createRef, useCallback} from 'react';
export const HelloWorld = () => {
const checkboxref = createRef();
const handleOnClick = useCallback(() => {
const node = checkboxref.current;
if(node){
node.focus();
node.select();
}
}, [checkboxref]);
return (
<div>
<button onClick={handleOnClick}>Focus</button>
<input type="checkbox" ref={checkboxref} />
</div>
);
};
select
方法选择文本输入和文本区域等元素中的文本,因此我不确定您期望它对复选框产生什么影响。至于 focus
,它可以聚焦,但同样,聚焦复选框也无能为力。我只能想到它的样式https://jsfiddle.net/4howanL2/1/
如果您想选择并聚焦它:
checkboxref.current.checked = true;
当你将其设置为checked = true时,它也会聚焦它