如何使用 React ref 聚焦并选择复选框?

问题描述 投票:0回答:4

我一直在寻找一种方法来正确地focusselectReact代码中的复选框。 我在下面的示例中使用的方法

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>
  );
};

当我单击按钮时,我的复选框未聚焦且未选中...

请问有什么解决办法吗?

非常感谢。

reactjs checkbox use-ref
4个回答
4
投票

您不需要创建单独的函数来处理 onChange 事件

const checkboxref = useRef(null);

您可以简单地获取复选框的当前值:

checkboxref.current.checked 
// which returns a boolean

2
投票

使用这个可能会对你有所帮助。在这里,我使用 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>
  );
};

1
投票

select
方法选择文本输入和文本区域等元素中的文本,因此我不确定您期望它对复选框产生什么影响。至于
focus
,它可以聚焦,但同样,聚焦复选框也无能为力。我只能想到它的样式https://jsfiddle.net/4howanL2/1/


0
投票

如果您想选择并聚焦它:

checkboxref.current.checked = true;

当你将其设置为checked = true时,它也会聚焦它

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.