-
用ref來觸達dom元素或組件實體
- ref是reference(參考)的簡寫,
- 在資料流之外直接操作子孫組件:
- ref屬性賦值給Html元素,那么this.ref.current就獲取到html元素
- ref屬性賦值給常規React組件,那么this.ref.current就獲取到組件的實體
- 不要過度使用:
- 有需要直接觸達和操作子孫組件實體或者操作子dom元素的情況,這時候應該使用React Ref,
- 如果屬性下傳能夠解決問題,應該使用宣告式的屬性傳遞,而非命令式的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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/177001.html
標籤:JavaScript
上一篇:TypeScript基礎型別
