網站首頁 編程語言 正文
useImperativeHandle的使用
你不能在函數組件上使用 ref 屬性,因為它們沒有實例:
import React, { Component } from 'react';
function MyFunctionComponent() {
? return <input />
}
class Parent extends React.Component {
? constructor(props) {
? ? super(props);
? ? this.textInput = React.createRef();
? }
? render() {
? ? return (
? ? ? <MyFunctionComponent ref={this.textInput} />
? ? );
? }
}
如果你需要使用 ref,你應該將組件轉化為一個 class,就像當你需要使用生命周期鉤子或 state 時一樣。
不管怎樣,你可以在函數組件內部使用 ref 屬性,只要它指向一個 DOM 元素或 class 組件:
function CustomTextInput(props) {
? // 這里必須聲明 textInput,這樣 ref 才可以引用它
? let textInput = React.createRef();
? function handleClick() {
? ? textInput.current.focus();
? }
? return (
? ? <div>
? ? ? <input
? ? ? ? type="text"
? ? ? ? ref={textInput} />
? ? ? <input
? ? ? ? type="button"
? ? ? ? value="Focus the text input"
? ? ? ? onClick={handleClick}
? ? ? />
? ? </div>
? );
}
在下面的示例中,MyFunctionComponent 使用 React.forwardRef 來獲取傳遞給它的 ref,然后轉發到它渲染的 DOM button:
const MyFunctionComponent = React.forwardRef((props, ref) => (
? <button ref={ref}>
? ? {props.children}
? </button>
))
class Parent extends React.Component {
? constructor(props) {
? ? super(props);
? ? this.textInput = React.createRef();
? }
? componentDidMount() {
? ? console.log(this.textInput.current)
? }
? render() {
? ? return (
? ? ? <MyFunctionComponent ref={this.textInput} />
? ? );
? }
}
第二個參數 ref 只在使用 React.forwardRef 定義組件時存在。常規函數和 class 組件不接收 ref 參數,且 props 中也不存在 ref。
useImperativeHandle
useImperativeHandle 可以讓你在使用 ref 時自定義暴露給父組件的實例值。useImperativeHandle 應當與 forwardRef 一起使用:?
const MyFunctionComponent = React.forwardRef((props, ref) => {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
}
}));
return (
<input ref={inputRef} />
)
})
class Parent extends React.Component {
constructor(props) {
super(props);
this.textInput = React.createRef();
}
componentDidMount() {
this.textInput.current.focus()
}
render() {
return (
<MyFunctionComponent ref={this.textInput} />
);
}
}
使用useImperativeHandle時父組件第一次沒拿到子組件方法
背景需求
一個tab兩個按鈕A、B,默認選中的A,當點擊到B時需要顯示B對應的圖表。考慮到B的圖表在頁面加載時已經初始化完成,所以點擊B時再調用圖表的resize方法。由于tab中的圖表是寫在子組件里,所以通過useImperativeHandle實現父組件調用子組件方法,React版本"react": "^18.1.0",代碼如下
父組件:?
const childRef = useRef()
const item = [{
? ? ? ? name: 'XXXX',
? ? ? ? content: <RunningRecord cRef={childRef} />,
? ? ? ? handClick: childRef.current?.resizeChart
}]
return <>
? ? ……
? ? <li onClick={() => {
? ? ? ? ? ? setTimeout(() => {
? ? ? ? ? ? ? ? console.log('~~item.handClick',item.handClick)
? ? ? ? ? ? ? ? item.handClick?.()
? ? ? ? ? ? }, 200)
? ? ? ? }}
? ? ? ? key={item.name}>
? ? ? ? {item.name}
? ? </li>
? ? ……
? ? <RunningRecord cRef={childRef} />
</>
子組件:
function RunningRecord({ cRef }) {
? ? ……
? ? useImperativeHandle(cRef,()=>({
? ? ? ? resizeChart:()=> {dosomething……}
? ? }))
問題
這樣寫在本地開發模式中正常運行,但生產環境中父組件首次加載不能拿到子組件的方法,需tab切換到A再次且到B才行。猜想原因,大概在生產環境中,父組件把子組件暴露出來的方法綁定到UI中的點擊事件中,而子組件初始化的時機晚,初始完成后并沒有把事件傳回來。
這個猜想不一定準確,歡迎知道的小伙伴們補充。
解決方法
在父組件中,將子組件賦值的過程放在useEffect中,不寫依賴項參數(不是沒有依賴的空數組),再運行,一切正常。
const usageRecordData = [{
? ? name: 'XXXX',
? ? content: <RunningRecord cRef={childRef} />,
}]
useEffect(() => {
? ? usageRecordData[1].handClick = childRef.current?.resizeChart
})
原文鏈接:https://wuqiang.blog.csdn.net/article/details/100079497
相關推薦
- 2022-05-24 C/C++中的static關鍵字詳解_C 語言
- 2022-10-06 C#中?MessageBox的使用技巧_C 語言
- 2022-10-14 eclipse創建maven項目
- 2024-07-13 IDEA無法使用@WebServlet()注解
- 2023-02-09 c++報錯問題解決方案lvalue?required?as?left?operand?of?assi
- 2023-07-18 A component required a bean of type ‘xxx‘ that cou
- 2022-09-02 Redis解決Session共享問題的方法詳解_Redis
- 2023-02-17 python中列表推導式與生成器表達式對比詳解_python
- 最近更新
-
- 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同步修改后的遠程分支