Lin Chen   ·  4年前
2 貼文  ·  7 留言

React Ref筆記

(Ref = reference)

Ref於React官方文件其實已經寫得很清楚了,但不自己記錄+附註,還是覺得沒有完全理解。

在一般的情況下,我們會使用props與state,在React的各個Component中進行資料上的變動(並render)。但我們也知道,React採用的是他們設計的Virtual DOM,也就是說,這個DOM並不是我們在html當中指稱的DOM,但偏偏,在很少數的情況下,我們就是想要去控制原始的DOM(且希望能決定要不要re-render)。最常見的情況(每個tutorial video)都會拿出來講的,就是將ref放進Component當中的input element。

當我們想要在網頁讀取後(或說componentDidMount後),自動聚焦(focus())在某個input框時,我們得先生出(宣告)一個ref,並將input加上ref這個attribute,再將ref(value)放進ref(attr)中(天阿好饒口),如下:

class MyComponent extends React.Component{
this.inputRef = React.createRef();
中略
<input ref={this.inputRef} />

在這個步驟中,我們已經將ref成功的指向input,之後便可透過控制this.inputRef來達成目的,也就是focus()。

通常,我們會在componentDidMount後使其聚焦:
componentDidMount(){ this.inputRef.current.focus() }
其中,我一直不確定this.inputRef到底是什麼,直到console.log後才知道,他是一個object,而這個object中只有一個current屬性
因此,需要透過this.inputRef.current,才可取得該node的各種methods與properties(這邊我們要的是focus())

ok,這樣就完成了使input在網頁(Component)載入後,自動聚焦的功能。

需要注意的是,這邊的ref不可以使用在function component,因為他們沒有instance。要用的話,有hook版:useRef可以使用,而且似乎更加靈活。
另外官方也強調,別在任何可以透過props、state的地方用ref,就算要用,也不要過度使用!

function component版的ref + focus :

callback ref:
callback ref的形式好像是比較早期的用法,可能會在以前的project看到

//這寫法滿奇怪的,但只能先記著

通常會先指派this.callbackInputRef = null;

再多寫
this.setCallbackInputRef = element =>{ this.callbackInputRef = element; }

再來,當然就是將ref放進input中,不過我們放的是有function的這個ref
<input ref={this.setCallbackInputRef}>

最後,在componentDidMount中使他聚焦:
componentDidMount(){ if(this.callbackInputRef) this.callbackInputRef.focus() }

之所以要先檢查this.callbackInputRef是否為true(不是null),是因為當Component mounted後,React會透過DOM element呼叫這個callback ref一次,在unmount時,會將null帶入,再呼叫一次(這句用英文講可能比較好懂...)
React will call the ref callback with the DOM element when the component MOUNT and call it with NULL when it unmount
值得注意的是,這邊就不需要用current了,可以直接呼叫該node所屬的method。

  分享   共 2,456 次點閱
按了喜歡:
共有 1 則留言
John Weng   ·  3年前
0 貼文  ·  1 留言

請問這邊 『原始的DOM』指的是 Real DOM 還是 virtual DOM?

 
您的留言
Lin Chen
2 貼文  ·  7 留言
查看所有文章