React中的ref屬性的使用示例詳解
ref 簡介
React提供的這個(gè)ref屬性,表示為對組件真正實(shí)例的引用,其實(shí)就是ReactDOM.render()返回的組件實(shí)例;需要區(qū)分一下,ReactDOM.render()渲染組件時(shí)返回的是組件實(shí)例;而渲染dom元素時(shí),返回是具體的dom節(jié)點(diǎn)。
例如,下面代碼:
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é)點(diǎn)
const { inputRef } = this.refs
// 輸出input值
console.log(inputRef.value);
}
render() {
return (
<div>
<input ref="inputRef" type="text" placeholder="點(diǎn)擊按鈕提示數(shù)據(jù)"/>
<button onClick={ this.showData }>點(diǎn)我提示輸入框值</button>
</div>
)
}
}2. create形式的ref
import React, { Component } from 'react'
export default class index extends Component {
// React.createRef調(diào)用后返回一個(gè)容器,存儲被ref標(biāo)識的節(jié)點(diǎn),單一使用。也就是說,沒定義一個(gè)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="點(diǎn)擊按鈕提示數(shù)據(jù)"/>
<button onClick={ this.showData }>點(diǎn)我提示輸入框值</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>
{/* 這里傳入一個(gè)回調(diào)函數(shù) */}
<input ref={ currentNode => this.inputRef = currentNode } type="text" placeholder="點(diǎn)擊按鈕提示數(shù)據(jù)"/>
<button onClick={ this.showData }>點(diǎn)我提示輸入框值</button>
</div>
)
}
}總結(jié):
綜合以上三種形式各有優(yōu)缺點(diǎn),方式1與方式2寫起來比較方便但是比較繁瑣,方式三通過傳入一個(gè)回調(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 實(shí)現(xiàn)類所有生命周期
react 自 16.8 開始,引入了 Hooks 概念,使得函數(shù)組件中也可以擁有自己的狀態(tài),并且可以模擬對應(yīng)的生命周期,這篇文章主要介紹了使用 React hooks 怎么實(shí)現(xiàn)類里面的所有生命周期,需要的朋友可以參考下2023-02-02
react中的useImperativeHandle()和forwardRef()用法
這篇文章主要介紹了react中的useImperativeHandle()和forwardRef()用法,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-08-08

