React中的ref屬性的使用示例詳解
ref 簡介
React提供的這個ref
屬性,表示為對組件真正實例的引用,其實就是ReactDOM.render()返回的組件實例
;需要區(qū)分一下,ReactDOM.render()
渲染組件時返回的是組件實例;而渲染dom元素時,返回是具體的dom節(jié)點。
例如,下面代碼:
const domCom = <button type="button">button</button>; const refDom = ReactDOM.render(domCom,container); //ConfirmPass的組件內(nèi)容省略 const refCom = ReactDOM.render(<ConfirmPass/>,container); console.log(refDom); console.log(refCom);
1. 字符串形式的ref
import React, { Component } from 'react' export default class index extends Component { showData = () => { // 獲取input節(jié)點 const { inputRef } = this.refs // 輸出input值 console.log(inputRef.value); } render() { return ( <div> <input ref="inputRef" type="text" placeholder="點擊按鈕提示數(shù)據(jù)"/> <button onClick={ this.showData }>點我提示輸入框值</button> </div> ) } }
2. create形式的ref
import React, { Component } from 'react' export default class index extends Component { // React.createRef調(diào)用后返回一個容器,存儲被ref標(biāo)識的節(jié)點,單一使用。也就是說,沒定義一個ref就要調(diào)用一次React.createRef inputRef = React.createRef() showData = () => { const refVal = this.inputRef.current console.log(refVal.value); } render() { return ( <div> <input ref={ this.inputRef } type="text" placeholder="點擊按鈕提示數(shù)據(jù)"/> <button onClick={ this.showData }>點我提示輸入框值</button> </div> ) } }
3. 回調(diào)函數(shù)形式的ref
import React, { Component } from 'react' export default class index extends Component { showData = () => { const { inputRef } = this console.log(inputRef.value); } render() { return ( <div> {/* 這里傳入一個回調(diào)函數(shù) */} <input ref={ currentNode => this.inputRef = currentNode } type="text" placeholder="點擊按鈕提示數(shù)據(jù)"/> <button onClick={ this.showData }>點我提示輸入框值</button> </div> ) } }
總結(jié):
綜合以上三種形式各有優(yōu)缺點,方式1與方式2寫起來比較方便但是比較繁瑣,方式三通過傳入一個回調(diào)函數(shù),不但簡化了操作還不失優(yōu)雅,顯得代碼逼格高些,但在最新版及以后的版本中,React官方使用函數(shù)式編程,所以更推薦使用create
形式的ref。
到此這篇關(guān)于React中的ref屬性的使用的文章就介紹到這了,更多相關(guān)React ref屬性使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用 React hooks 實現(xiàn)類所有生命周期
react 自 16.8 開始,引入了 Hooks 概念,使得函數(shù)組件中也可以擁有自己的狀態(tài),并且可以模擬對應(yīng)的生命周期,這篇文章主要介紹了使用 React hooks 怎么實現(xiàn)類里面的所有生命周期,需要的朋友可以參考下2023-02-02react中的useImperativeHandle()和forwardRef()用法
這篇文章主要介紹了react中的useImperativeHandle()和forwardRef()用法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-08-08