學習React中ref的兩個demo示例
為了擺脫繁瑣的Dom操作, React提倡組件化, 組件內部用數據來驅動視圖的方式,來實現(xiàn)各種復雜的業(yè)務邏輯 ,然而,當我們?yōu)樵糄om綁定事件的時候, 還需要通過組件獲取原始的Dom, 而React也提供了ref為我們解決這個問題.
為什么不能從組件直接獲取Dom?
組件并不是真實的 DOM 節(jié)點,而是存在于內存之中的一種數據結構,叫做虛擬 DOM (virtual DOM)。只有當它插入文檔以后,才會變成真實的 DOM
如果需要從組件獲取真實 DOM 的節(jié)點,就要用到官方提供的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動畫演示
使用場景
為了更好的展示用戶輸入的銀行卡號, 需要每隔四個數字加一個空格
實現(xiàn)思路:
當用戶輸入的字符個數, 可以被5整除時, 額外加一個空格
當用戶刪除數字時,遇到空格, 要移除兩個字符(一個空格, 一個數字),
為了實現(xiàn)以上想法, 必須獲取鍵盤的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原生的事件綁定機制最好用~
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
React組件實例三大核心屬性State props Refs詳解
組件實例的三大核心屬性是:State、Props、Refs。類組件中這三大屬性都存在。函數式組件中訪問不到 this,也就不存在組件實例這種說法,但由于它的特殊性(函數可以接收參數),所以存在Props這種屬性2022-12-12詳解在React中跨組件分發(fā)狀態(tài)的三種方法
這篇文章主要介紹了詳解在React中跨組件分發(fā)狀態(tài)的三種方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-08-08React?Native實現(xiàn)Toast輕提示和loading效果
這篇文章主要介紹了React Native實現(xiàn)Toast輕提示和loading效果,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-09-09