網(wǎng)站首頁 編程語言 正文
在工作中遇到一個這個小功能,就是當(dāng)用戶從A輸入框中失焦后,要去判斷當(dāng)前的焦點(diǎn)是否在B輸入框中,如果是的話需要做一些特殊操作.其實(shí)實(shí)現(xiàn)起來很簡單,就是使用ref配合document.activeElement方法即可實(shí)現(xiàn),以下是實(shí)現(xiàn)的具體邏輯
import React from "react";
// 當(dāng)在A輸入框中失焦之后,要判斷當(dāng)前焦點(diǎn)是否在B輸入框中
export default class App extends React.Component {
constructor(props) {
super(props);
this.txt = {
curren: null,
};
}
// 當(dāng)A組件失焦后觸發(fā)
blur_handler = () => {
setTimeout(() => {
// 獲取當(dāng)前選中的元素
const focus = document.activeElement;
// 判斷當(dāng)前選中元素是否為B輸入框
if (focus === this.txt) {
console.log("當(dāng)前焦點(diǎn)聚焦在B輸入框中");
}else{
console.log("當(dāng)前焦點(diǎn)聚焦不在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:因?yàn)槲以诠ぷ髦惺褂玫膇nput元素是經(jīng)過第三方庫去處理過的,所以當(dāng)使用ref獲取到該元素時,獲取到的并不是input元素本身,而是將input元素包裹了一層的對象,那么此時可以使用.input的方式去獲取真正的input元素.如果使用以上方法不能獲取到對應(yīng)dom元素的話,不妨像我這樣操作下試試~
原文鏈接:https://blog.csdn.net/huanan__/article/details/126950725
相關(guān)推薦
- 2022-06-09 FreeRTOS實(shí)時操作系統(tǒng)的任務(wù)創(chuàng)建與任務(wù)切換_操作系統(tǒng)
- 2024-04-08 啟動spring-boot出現(xiàn)Error creating bean with name ‘conf
- 2022-07-29 Linux磁盤管理方法介紹_linux shell
- 2022-05-24 Golang?錯誤捕獲Panic與Recover的使用_Golang
- 2022-04-09 Linux普通用戶使用sudo顯示權(quán)限不足,admin is not in the sudoers
- 2022-10-05 python?slack桌面自動化開發(fā)工具_(dá)python
- 2022-10-21 Android基于Mapbox?V10?繪制LineGradient軌跡_Android
- 2023-03-19 Python學(xué)習(xí)之configparser模塊的使用詳解_python
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支