網站首頁 編程語言 正文
一、useImperativeHandle()
useImperativeHandle(ref, createHandle, [deps])
useImperativeHandle 可以讓你在使用 ref 時自定義暴露給父組件的實例值。在大多數情況下,應當避免使用 ref
這樣的命令式代碼。 useImperativeHandle 應當與 forwardRef 一起使用。
function FancyInput(props, ref) {
? const inputRef = useRef();
? useImperativeHandle(ref, () => ({
? ? focus: () => {
? ? ? inputRef.current.focus();
? ? }
? }));
? return <input ref={inputRef} ... />;
}
FancyInput = forwardRef(FancyInput);
在本例中,渲染 的父組件可以調用 inputRef.current.focus()。
二、forwardRef()
React.forwardRef 會創建一個React組件,這個組件能夠將其接受的 ref 屬性轉發到其組件樹下的另一個組件中。
這種技術并不常見,但在以下兩種場景中特別有用:
(1)轉發 refs 到 DOM 組件
(2)在高階組件中轉發 refs
React.forwardRef 接受渲染函數作為參數。React 將使用 props 和 ref 作為參數來調用此函數。此函數應返回 React 節點。 FancyButton 使用 React.forwardRef 來獲取傳遞給它的 ref,然后轉發到它渲染的 DOM button。這樣,使用 FancyButton 的組件可以獲取底層 DOM 節點 button 的 ref,并在必要時訪問,就像其直接使用 DOM button 一樣。
const FancyButton = React.forwardRef((props, ref) => ( ? // Step:3
? <button ref={ref} className="FancyButton"> ? ?// Step:4
? ? ? {props.children}
? </button>
));
const ref = React.createRef(); // Step:1
<FancyButton ref={ref}>Click me!</FancyButton>; // Step:2
在上述的示例中,React 會將 <FancyButton ref={ref}> 元素的 ref 作為第二個參數傳遞給 React.forwardRef 函數中的渲染函數。該渲染函數會將 ref 傳遞給 <button ref={ref}> 元素。 因此,當React 附加了 ref 屬性之后,ref.current 將直接指向 <button> DOM 元素實例。 欲了解更多相關信息,請參閱官檔 refs 轉發。
以下是對上述示例發生情況的逐步解釋:(轉發 refs 到 DOM 組件)
- 我們通過調用 React.createRef 創建了一個 React ref 并將其賦值給 ref 變量。
- 我們通過指定 ref 為JSX 屬性,將其向下傳遞給 <FancyButton ref={ref}>。
- React 傳遞 ref 給 forwardRef 內函數 (props, ref) => ...,作為其第二個參數。
- 我們向下轉發該 ref 參數到 <button ref={ref}>,將其指定為 JSX 屬性。
- 當 ref 掛載完成,ref.current 將指向 <button> DOM 節點。
三、案例
父組件
1、注冊
2、定義
3、觸發
子組件
1、暴露子組件方法,將 forwardRef 接受的 ref 屬性轉發到其組件樹下的另一個組件中
(1)
(2)
(3)父組件
原文鏈接:https://blog.csdn.net/qq_43392573/article/details/123735841
相關推薦
- 2022-03-18 linux下修改文件權限chmod命令詳細解析_Linux
- 2022-05-27 android實現簡單拼圖游戲_Android
- 2022-11-12 c++自定義sort()函數的排序方法介紹_C 語言
- 2022-08-15 ArrayList和LinkedList和Vector的區別
- 2024-04-08 nvm 在 Windows 上的使用
- 2022-11-01 python一行輸入多值的實現詳解_python
- 2022-10-05 Android?Flutter實現原理淺析_Android
- 2023-03-19 C語言實現求解素數的N種方法總結_C 語言
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支