学无先后,达者为师

网站首页 编程语言 正文

React - 判断焦点是否在某个元素上

作者:WHOVENLY 更新时间: 2022-10-11 编程语言

在工作中遇到一个这个小功能,就是当用户从A输入框中失焦后,要去判断当前的焦点是否在B输入框中,如果是的话需要做一些特殊操作.其实实现起来很简单,就是使用ref配合document.activeElement方法即可实现,以下是实现的具体逻辑

import React from "react";
// 当在A输入框中失焦之后,要判断当前焦点是否在B输入框中
export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.txt = {
      curren: null,
    };
  }
  // 当A组件失焦后触发
  blur_handler = () => {
    setTimeout(() => {
      // 获取当前选中的元素
      const focus = document.activeElement;
      // 判断当前选中元素是否为B输入框
      if (focus === this.txt) {
        console.log("当前焦点聚焦在B输入框中");
      }else{
        console.log("当前焦点聚焦不在B输入框中");
      }
    });
  };
  getBRef = (el) => {
    this.txt = el;
  };
  render() {
    return (
      <div>
        <input type="text" placeholder="A输入框" onBlur={this.blur_handler} />
        <input type="text" placeholder="B输入框" ref={this.getBRef} />
      </div>
    );
  }
}

tips:因为我在工作中使用的input元素是经过第三方库去处理过的,所以当使用ref获取到该元素时,获取到的并不是input元素本身,而是将input元素包裹了一层的对象,那么此时可以使用.input的方式去获取真正的input元素.如果使用以上方法不能获取到对应dom元素的话,不妨像我这样操作下试试~

原文链接:https://blog.csdn.net/huanan__/article/details/126950725

栏目分类
最近更新