為了擺脫繁瑣的Dom操作, React提倡組件化, 組件內部用數據來驅動視圖的方式,來實現各種復雜的業務邏輯 ,然而,當我們為原始Dom綁定事件的時候, 還需要通過組件獲取原始的Dom, 而React也提供了ref為我們解決這個問題.
為什么不能從組件直接獲取Dom?
組件并不是真實的 DOM 節點,而是存在于內存之中的一種數據結構,叫做虛擬 DOM (virtual DOM)。只有當它插入文檔以后,才會變成真實的 DOM
如果需要從組件獲取真實 DOM 的節點,就要用到官方提供的ref屬性
使用場景
當用戶加載頁面后, 默認聚焦到input框
import React, { Component } from 'react'; import './App.css'; // React組件準確捕捉鍵盤事件的demo class App extends Component { constructor(props) { super(props) this.state = { showTxt: "" } this.inputRef = React.createRef(); } // 為input綁定事件 componentDidMount(){ this.inputRef.current.addEventListener("keydown", (event)=>{ this.setState({showTxt: event.key}) }) // 默認聚焦input輸入框 this.inputRef.current.focus() } render() { return ( <div className="app"> <input ref={this.inputRef}/> <p>當前輸入的是: <span>{this.state.showTxt}</span></p> </div> ); } } export default App;
自動聚焦input動畫演示
使用場景
為了更好的展示用戶輸入的銀行卡號, 需要每隔四個數字加一個空格
實現思路:
當用戶輸入的字符個數, 可以被5整除時, 額外加一個空格
當用戶刪除數字時,遇到空格, 要移除兩個字符(一個空格, 一個數字),
為了實現以上想法, 必須獲取鍵盤的BackSpace事件, 重寫刪除的邏輯
限制為數字, 隔四位加空格
import React, { Component } from 'react'; import './App.css'; // React組件準確捕捉鍵盤事件的demo class App extends Component { constructor(props) { super(props) this.state = { showTxt: "" } this.inputRef = React.createRef(); this.changeShowTxt = this.changeShowTxt.bind(this); } // 為input綁定事件 componentDidMount(){ this.inputRef.current.addEventListener("keydown", (event)=>{ this.changeShowTxt(event); }); // 默認聚焦input輸入框 this.inputRef.current.focus() } // 處理鍵盤事件 changeShowTxt(event){ // 當輸入刪除鍵時 if (event.key === "Backspace") { // 如果以空格結尾, 刪除兩個字符 if (this.state.showTxt.endsWith(" ")){ this.setState({showTxt: this.state.showTxt.substring(0, this.state.showTxt.length-2)}) // 正常刪除一個字符 }else{ this.setState({showTxt: this.state.showTxt.substring(0, this.state.showTxt.length-1)}) } } // 當輸入數字時 if (["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"].includes(event.key)){ // 如果當前輸入的字符個數取余為0, 則先添加一個空格 if((this.state.showTxt.length+1)%5 === 0){ this.setState({showTxt: this.state.showTxt+' '}) } this.setState({showTxt: this.state.showTxt+event.key}) } } render() { return ( <div className="app"> <p>銀行卡號 隔四位加空格 demo</p> <input ref={this.inputRef} value={this.state.showTxt}/> </div> ); } } export default App;
小結:
虛擬Dom雖然能夠提升網頁的性能, 但虛擬 DOM 是拿不到用戶輸入的。為了獲取文本輸入框的一些操作, 還是js原生的事件綁定機制最好用~
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com