-
Ref 和Dom
- ref是reference(引用)的簡寫。
- 能力:大多數情況下,props向下遞可以解決一切問題,但是依然有需要觸達子組件React實例或者操作子孫組件Dom節點的情況,這時候應該使用React Ref。
- 使用場景:
- 用來處理立即執行的動畫,(我們知道流暢的動畫需要DOM節點(D3.js)或者node節點(cocos.js))。
- 用來處理非受控組件的焦點,什么是受控/非受控組件參考文章。
- 用來與第三方庫對接,我知道的有d3 或者 cocos,因為第三方庫需要獲取dom或者節點。
-
React.forwardRef((props,ref)=><Compnent>)
- 簡而言之就是自動透傳引用(Ref),能讓組件接收傳過來的ref, 向下(或者說向前)傳遞Ref。
const FancyButton = React.forwardRef((props, ref) => ( <button ref={ref} className="FancyButton"> {props.children} </button> )); // You can now get a ref directly to the DOM button:
// 現在你可以獲取DOM按鈕的引用 const ref = React.createRef(); <FancyButton ref={ref}>Click me!</FancyButton>; -
上述代碼的解釋:
- 首先創建了一個ref, 這個ref的目的就是抓到子組件中的<button>DOM節點
- 通過組件jsx屬性把ref傳給子組件<FancyButton>,這一行
<FancyButton ref={ref}>Click me!</FancyButton>;
- FancyButton組件通過React.forwardRef透傳props和ref,這里ref才是我們要注意的點。
- 參數ref賦值給子組件<button>
- 當ref關聯上之后,這個ref.current將指向<button>的DOM節點。
- 簡而言之就是自動透傳引用(Ref),能讓組件接收傳過來的ref, 向下(或者說向前)傳遞Ref。
-
React.forwardRef((props, ref)=><Componnet>)在高階組件中的使用:
- 比如我們寫一個打印前后屬性的高階組件logProps,這個高階組件能夠透傳ref
1 function logProps(Component) { 2 class LogProps extends React.Component { 3 componentDidUpdate(prevProps) { 4 console.log('old props:', prevProps); 5 console.log('new props:', this.props); 6 } 7 8 render() { 9 const {forwardedRef, ...rest} = this.props; 11 // 把常規屬性"forwardedRef"作為ref賦值給傳過來的Component組件 12 return <Component ref={forwardedRef} {...rest} />; 13 } 14 } 15 16 // 注意React.forwardRef提供的第二個參數ref. 17 // 我們可以把ref作為一個常規屬性"forwardedRef"傳給LogProps這個組件 18 // 就可以跟實例綁定. 19 return React.forwardRef((props, ref) => { 20 return <LogProps {...props} forwardedRef={ref} />; 21 }); 22 }
- 比如我們寫一個打印前后屬性的高階組件logProps,這個高階組件能夠透傳ref