React之ref操作DOM(ref = {input=>this.input = input})


學習react的同學肯定看過這種寫法

 

注意這里的ref,寫法為

ref = {(input)=>{this.input=input}}
等價於
ref = {input=>this.input=input}
等價於
ref = {(input)=>this.input=input}

這里主要是ES6箭頭函數arrow function和React語法的結合。

 

知識點1、

  

 

 

知識點2、

  React官方說法

1、我們給 input 元素加了一個 ref 屬性,這個屬性值是一個函數。當 input 元素在頁面上掛載完成以后,React.js 就會調用這個函數,並且把這個掛載以后的 DOM 節點傳給這個函數。
  在函數中我們把這個 DOM 元素設置為組件實例的一個屬性,這樣以后我們就可以通過 this.input 獲取到這個 DOM 元素。 2、然后我們就可以在 componentDidMount 中使用這個 DOM 元素,並且調用 this.input.focus() 的 DOM API。整體就達到了頁面加載完成就自動 focus 到輸入框的功能
  (大家可以注意到我們用上了 componentDidMount 這個組件生命周期)。 3、我們可以給任意代表 HTML 元素標簽加上
ref 從而獲取到它 DOM 元素然后調用 DOM API。但是記住一個原則:能不用 ref 就不用。特別是要避免用 ref 來做 React.js
  本來就可以幫助你做到的頁面自動更新的操作和事件監聽。多余的 DOM 操作其實是代碼里面的“噪音”,不利於我們理解和維護。

  

 

其他:

React 中ref的幾種用法
1.字符串
通過 this.refs.a 來引用真實dom的節點---dom 節點上使用
<input  type ="text" ref="a"/> 


2.回調函數 回調函數就是在dom節點或組件上掛載函數,函數的入參是dom節點或組件實例,達到的效果與字符串形式是一樣的,都是獲取其引用。 <input type="text" ref={(input)=>{this.textInput=input}}

3.React.createRef() 在React 16.3版本后,使用此方法來創建ref。將其賦值給一個變量,通過ref掛載在dom節點或組件上,該ref的current屬性將能拿到dom節點或組件的實例 class Counter extends Component { constructor() { super() this.state ={sum:0,number:0} this.myRef = React.createRef(); } change = () =>{ this.setState({...this.state,sum: Number(this.textInput.value) + Number(this.myRef.current.value)}) } componentDidMount(){ console.log(this.myRef.current.value); } render() { return ( <div onChange ={this.change} > <input type="text" ref={(input)=>{this.textInput=input}} />+ <input type ="text" ref={this.myRef} /> = {this.state.sum} </div> ) } }

 

 

 

  

 

 

 

 

.

React 中ref的幾種用法1.字符串通過 this.refs.a 來引用真實dom的節點dom 節點上使用
 <input  type ="text" ref="a"/> 12.回調函數回調函數就是在dom節點或組件上掛載函數,函數的入參是dom節點或組件實例,達到的效果與字符串形式是一樣的,都是獲取其引用。
<input type="text" ref={(input)=>{this.textInput=input}} 13.React.createRef()在React 16.3版本后,使用此方法來創建ref。將其賦值給一個變量,通過ref掛載在dom節點或組件上,該ref的current屬性將能拿到dom節點或組件的實例
class Counter extends Component {    constructor() {        super()        this.state ={sum:0,number:0}        this.myRef = React.createRef();    }    change = () =>{        this.setState({...this.state,sum: Number(this.textInput.value) + Number(this.myRef.current.value)})    }    componentDidMount(){        console.log(this.myRef.current.value);    }    render() {        return (            <div onChange ={this.change} >                <input type="text" ref={(input)=>{this.textInput=input}} />+                 <input  type ="text" ref={this.myRef} /> = {this.state.sum}            </div>                    )    }}————————————————版權聲明:本文為CSDN博主「zhang_xin_new」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。原文鏈接:https://blog.csdn.net/zhang_xin_new/article/details/91458022


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM