React中的Refs屬性你來了解嗎
1 介紹
react組件的三大屬性:
1.props
屬性:封裝傳遞給組件的參數(shù)
2.state
屬性:組件的狀態(tài),當(dāng)值發(fā)生改變后,重新渲染組件
3.refs
屬性:
(1)通過該屬性可以去訪問DOM元素或render函數(shù)中的react元素(虛擬的DOM元素) ——DOM元素或render函數(shù)中的react元素的代理(句柄)
(2)本質(zhì)是ReactDOM.render()
函數(shù)返回的實(shí)例(組件實(shí)例或DOM節(jié)點(diǎn))
Refs在計算機(jī)中稱為彈性文件系統(tǒng)。React中的Refs提供了一種方式,允許我們訪問DOM節(jié)點(diǎn)或在render方法中創(chuàng)建的React元素。本質(zhì)為ReactDOM.render()
返回的組件實(shí)例,如果是渲染組件則返回的是組件實(shí)例,如果渲染dom則返回的是具體的dom節(jié)點(diǎn)。
作用:Refs時React提供給我們安全訪問DOM元素或者某個組件實(shí)例的句柄。在類組件中,React將ref屬性中第一個參數(shù)作為DOM中的句柄。在函數(shù)組件中,React用hooks的api useRef也能獲得ref。
2 使用方法
2.1 createRef(版本>=React16.3)
一般在構(gòu)造函數(shù)中將refs分配給實(shí)例屬性,以供組件的其他方法中使用。
1、對于html元素:可以獲取元素實(shí)例
示例代碼:
class Refs extends React.Component { constructor(props) { super(props); // 在構(gòu)造函數(shù)中初始化一個ref,然后在return中就可以使用了 this.myRef = React.createRef(); console.log(this.myRef); } componentDidMount() { // 在render()函數(shù)執(zhí)行完成后調(diào)用 this.myRef.current.innerHTML = "橘貓吃不胖"; // this.myRef中有一個current屬性 } render() { return ( <div> {/*如果ref屬性被用于html,那么它的值就是底層DOM元素*/} <div ref={this.myRef}></div> </div> ); } }
2、可以和類組件進(jìn)行綁定 —— 代表類組件的實(shí)例
示例代碼:
class Refs extends React.Component { constructor(props) { super(props); this.myRef = React.createRef(); } componentDidMount() { // 在父組件中調(diào)用了子組件的方法 this.myRef.current.change(); } render() { return <Children ref={this.myRef}/> } } class Children extends React.Component { change() { console.log("橘貓吃不胖變身"); } render() { return <span>橘貓吃不胖</span> } }
2.2 回調(diào)Refs
React將在組件掛載時,會調(diào)用ref回調(diào)函數(shù)并傳入DOM怨怒是,當(dāng)卸載時調(diào)用它并傳入null。早componentDidMount或componentDidUpdate觸發(fā)前,React會保證refs一定是最新的。
示例代碼:
class Refs extends React.Component { constructor(props) { super(props); this.targetRef = null; this.myRef = (e) => this.targetRef = e; } componentDidMount() { console.log("this.refs" + this.refs.container); } render() { return <div ref={this.myRef}> 橘貓吃不胖 </div> } }
2.3 String類型的Refs(已過時,不推薦使用)
示例代碼:
class Refs extends React.Component { constructor(props) { super(props); this.targetRef = null; this.myRef = (e) => this.targetRef = e; } componentDidMount() { console.log("this.refs" + this.refs.container); } render() { return <div ref={this.myRef}> 橘貓吃不胖 </div> } }
2.4 useRef(React Hooks)
function HookRef(props) { const inputElement = useRef(); return ( <div> <input ref={inputElement}/> <button onClick={() => { inputElement.current.focus() }}>獲得焦點(diǎn) </button> </div> ) }
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
react進(jìn)階教程之異常處理機(jī)制error?Boundaries
在react中一旦出錯,如果每個組件去處理出錯情況則比較麻煩,下面這篇文章主要給大家介紹了關(guān)于react進(jìn)階教程之異常處理機(jī)制error?Boundaries的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-08-08React useContext與useReducer函數(shù)組件使用
useContext和useReducer 可以用來減少層級使用, useContext,可以理解為供貨商提供一個公共的共享值,然后下面的消費(fèi)者去接受共享值,只有一個供貨商,而有多個消費(fèi)者,可以達(dá)到共享的狀態(tài)改變的目的2023-02-02