React中的ref屬性的使用示例詳解
ref 簡(jiǎn)介
React提供的這個(gè)ref
屬性,表示為對(duì)組件真正實(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è)容器,存儲(chǔ)被ref標(biāo)識(shí)的節(jié)點(diǎn),單一使用。也就是說(shuō),沒(méi)定義一個(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寫(xiě)起來(lái)比較方便但是比較繁瑣,方式三通過(guò)傳入一個(gè)回調(diào)函數(shù),不但簡(jiǎn)化了操作還不失優(yōu)雅,顯得代碼逼格高些,但在最新版及以后的版本中,React官方使用函數(shù)式編程,所以更推薦使用create
形式的ref。
到此這篇關(guān)于React中的ref屬性的使用的文章就介紹到這了,更多相關(guān)React ref屬性使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
nginx配置React靜態(tài)頁(yè)面的方法教程
作為一個(gè)前端開(kāi)發(fā)時(shí)刻想著,怎么把自己寫(xiě)的東西,丟到自己的服務(wù)器上面,然后展示給別人看。下面我就簡(jiǎn)單直白的寫(xiě)下,這篇文章主要給大家介紹了關(guān)于nginx配置React靜態(tài)頁(yè)面的方法教程,需要的朋友可以參考下。2017-11-11使用 React hooks 實(shí)現(xiàn)類(lèi)所有生命周期
react 自 16.8 開(kāi)始,引入了 Hooks 概念,使得函數(shù)組件中也可以擁有自己的狀態(tài),并且可以模擬對(duì)應(yīng)的生命周期,這篇文章主要介紹了使用 React hooks 怎么實(shí)現(xiàn)類(lèi)里面的所有生命周期,需要的朋友可以參考下2023-02-02react中的useImperativeHandle()和forwardRef()用法
這篇文章主要介紹了react中的useImperativeHandle()和forwardRef()用法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-08-08