ref
Refs 提供了一種方式馆里,允許我們?cè)L問(wèn) DOM 節(jié)點(diǎn)或在 render 方法中創(chuàng)建的 React 元素
Refs 是使用 React.createRef() 創(chuàng)建的衣厘,并通過(guò) ref 屬性附加到 React 元素假夺。在構(gòu)造組件時(shí),通常將 Refs 分配給實(shí)例屬性疲憋,以便可以在整個(gè)組件中引用它們控漠。
當(dāng) ref 被傳遞給 render
中的元素時(shí)洛波,對(duì)該節(jié)點(diǎn)的引用可以在 ref 的 current
屬性中被訪問(wèn)巩搏。
const node = this.myRef.current;
ref 的值根據(jù)節(jié)點(diǎn)的類(lèi)型而有所不同:
當(dāng)
ref
屬性用于 HTML 元素時(shí)扒秸,構(gòu)造函數(shù)中使用React.createRef()
創(chuàng)建的ref
接收底層 DOM 元素作為其current
屬性播演。當(dāng)
ref
屬性用于自定義 class 組件時(shí),ref
對(duì)象接收組件的掛載實(shí)例作為其current
屬性伴奥。-
你不能在函數(shù)組件上使用
ref
屬性写烤,因?yàn)樗麄儧](méi)有實(shí)例,但是可以用useRef來(lái)獲取節(jié)點(diǎn)拾徙。function CustomTextInput(props) { // 這里必須聲明 textInput洲炊,這樣 ref 才可以引用它 const textInput = useRef(null); function handleClick() { textInput.current.focus(); } return ( <div> <input type="text" ref={textInput} /> <input type="button" value="Focus the text input" onClick={handleClick} /> </div> ); }
使用場(chǎng)景
- 管理焦點(diǎn),文本選擇或媒體播放尼啡。
- 觸發(fā)強(qiáng)制動(dòng)畫(huà)暂衡。
- 集成第三方 DOM 庫(kù)。
避免使用 refs 來(lái)做任何可以通過(guò)聲明式實(shí)現(xiàn)來(lái)完成的事情
盡量不要向父組件暴露子組件DOM refs崖瞭,這就違背了封裝的原則狂巢,如果子組件的工作必須依賴于父組件,那為什么不寫(xiě)成一個(gè)組件呢书聚。但是官方文檔里也沒(méi)把話說(shuō)死唧领,因?yàn)樵跇O少數(shù)的業(yè)務(wù)情景之下藻雌,我們必須干這個(gè)事情才能實(shí)現(xiàn)某些功能,比如在高階組件中斩个,我們可以通過(guò)ref來(lái)獲得組件實(shí)例胯杭,在父組件中去執(zhí)行屬于子組件實(shí)例的一些方法。
回調(diào)Refs
它能助你更精細(xì)地控制何時(shí) refs 被設(shè)置和解除萨驶。
傳遞一個(gè)函數(shù)歉摧。這個(gè)函數(shù)中接受 React 組件實(shí)例或 HTML DOM 元素作為參數(shù),以使它們能在其他地方被存儲(chǔ)和訪問(wèn)腔呜。
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
this.textInput = null;
this.setTextInputRef = element => { this.textInput = element; };
this.focusTextInput = () => { // 使用原生 DOM API 使 text 輸入框獲得焦點(diǎn)
if (this.textInput) this.textInput.focus();
};
}
componentDidMount() {
// 組件掛載后,讓文本框自動(dòng)獲得焦點(diǎn)
this.focusTextInput(); }
render() {
// 使用 `ref` 的回調(diào)函數(shù)將 text 輸入框 DOM 節(jié)點(diǎn)的引用存儲(chǔ)到 React
// 實(shí)例上(比如 this.textInput)
return (
<div>
<input
type="text"
ref={this.setTextInputRef} />
<input
type="button"
value="Focus the text input"
onClick={this.focusTextInput} />
</div>
);
}
}
它的執(zhí)行時(shí)機(jī)是:
- 組件被掛載后(componentDidMount)再悼,回調(diào)函數(shù)立即執(zhí)行核畴,回調(diào)函數(shù)的參數(shù)為該組件的實(shí)例。
- 組件被卸載(componentDidUnmount)或者原有的 ref 屬性本身發(fā)生變化的時(shí)候冲九,此時(shí)回調(diào)函數(shù)也會(huì)立即執(zhí)行谤草,且回調(diào)函數(shù)的參數(shù)為 null。