【问题标题】:How to focus and select a checkbox using React ref?如何使用 React ref 聚焦和选择复选框?
【发布时间】: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>
  );
};

当我点击按钮时,我的复选框没有聚焦,也没有被选中...

请问有什么解决办法吗?

非常感谢。

【问题讨论】:

  • 您单击一个按钮,我敢打赌,在您释放鼠标按钮后该按钮具有焦点。尝试启动一个计时器,看看它是否有效

标签: reactjs checkbox use-ref


【解决方案1】:

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

【讨论】:

  • 我不知道我们也可以在函数组件中使用createRef()。但是不知道这两个函数有什么区别?
【解决方案2】:

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

【讨论】:

  • 嗨,非常感谢。我没有为我的复选框输入设置焦点样式,这就是为什么我没有看到任何效果:)
  • select 方法上,我认为它可能是允许勾选复选框的方法
  • 乐于助人!如果你想检查你的复选框,你需要这样做checkboxref.current.checked=true;
【解决方案3】:

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

const checkboxref = useRef(null);

您可以通过以下方式简单地获取复选框的当前值:

checkboxref.current.checked 
// which returns a boolean

【讨论】:

    猜你喜欢
    • 2018-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-16
    • 2020-12-25
    • 2018-01-12
    • 2021-10-06
    相关资源
    最近更新 更多