使用React.forwardRef傳遞泛型參數(shù)
React.forwardRef傳遞泛型參數(shù)
使用React函數(shù)組件開(kāi)發(fā)的過(guò)程中會(huì)遇到父組件調(diào)用子組件的方法或者屬性的場(chǎng)景,首次先說(shuō)怎么通過(guò)React.forwardRef來(lái)將子組件的屬性或者方法暴露給父組件
使用forwardRef暴露組建的方法和屬性
子組件
import { Box, Typography } from "@mui/material"; import { forwardRef, useImperativeHandle } from "react"; interface LocationChildProps { data: string; } export interface LocationChildRef { sayType(): void; } const LocationChild = forwardRef<LocationChildRef, LocationChildProps>((props, ref) => { useImperativeHandle(ref, () => ({ sayType() { console.log("子組件的data是 " + typeof props.data); }, })); return ( <Box> <Typography>{typeof props.data}</Typography> </Box> ); }); export default LocationChild;
在子組件中我們需要接受一個(gè)key為data的props,然后在子組件中展示這個(gè)值,并且通過(guò)useImperativeHandle向外暴露一個(gè)sayType的方法, 最后用forwardRef將子組件封裝然后暴露出去,這里forwardRef的作用就是包裝該組件為一個(gè)可以通過(guò)Ref訪問(wèn)的組件。
父組件
import { Button } from "@mui/material"; import { useRef } from "react"; import ConfigDetailContainer from "../options/ConfigDetailContainer"; import LocationChild, { LocationChildRef } from "./LocationChild"; export default function DeviceLocation() { const locationChildRef = useRef<LocationChildRef>(); const handleClick = () => { locationChildRef.current.sayType() // 輸出: 子組件的type是 string }; return ( <ConfigDetailContainer title="device.configTabs.LOCATION_HISTORY"> <LocationChild ref={locationChildRef} data="asdafaf"></LocationChild> <Button onClick={handleClick}>查看子組件的type的類(lèi)型</Button> </ConfigDetailContainer> ); }
父組件中需要通過(guò)useRef來(lái)創(chuàng)建ref并傳遞給子組件,這樣父子組件就建立了連接,父組件可以通過(guò)ref來(lái)訪問(wèn)子組件中自定義暴露的屬性或方法。
這里的操作就是父組件點(diǎn)擊按鈕控制臺(tái)打印子組件接收到的data這個(gè)prop的類(lèi)型。
泛型參數(shù)
現(xiàn)在新的問(wèn)題就是我們的父組件傳遞的data的類(lèi)型不是固定的,這時(shí)候子組件就要將data的類(lèi)型用泛型來(lái)定義,所以這里就有了fowardRef傳遞泛型參數(shù)的問(wèn)題:
我們可以這樣改造子組件,思路就是將這個(gè)組件改為工廠hansh的生成模式:
import { Box, Typography } from "@mui/material"; import { forwardRef, useImperativeHandle } from "react"; export interface LocationChildProps<T = string> { data: T; } export interface LocationChildRef { sayType(): void; } const LocationChild = function <T>() { return forwardRef<LocationChildRef, LocationChildProps<T>>((props, ref) => { useImperativeHandle(ref, () => ({ sayType() { console.log("子組件的data是 " + typeof props.data); }, })); return ( <Box> <Typography>{typeof props.data}</Typography> </Box> ); }); }; export default LocationChild;
然后在父組件中使用
import { Button } from "@mui/material"; import { PropsWithRef, useRef } from "react"; import ConfigDetailContainer from "../options/ConfigDetailContainer"; import LocationChild, { LocationChildProps, LocationChildRef } from "./LocationChild"; export default function DeviceLocation() { const locationChildRefString = useRef<LocationChildRef>(); const locationChildRefBoolean = useRef<LocationChildRef>(); const handleClick = () => { locationChildRefString.current.sayType(); locationChildRefBoolean.current.sayType(); }; const LocationChildComponent = LocationChild<string>(); const createComponent = function <T>(props: PropsWithRef<any>, ref: React.MutableRefObject<LocationChildRef>) { const Mycomponent = LocationChild<T>(); return <Mycomponent ref={ref} {...props}></Mycomponent>; }; return ( <ConfigDetailContainer title="device.configTabs.LOCATION_HISTORY"> <LocationChildComponent ref={locationChildRefString} data={"123"}></LocationChildComponent> {createComponent({ data: true }, locationChildRefBoolean)} <Button onClick={handleClick}>查看子組件的type的類(lèi)型</Button> </ConfigDetailContainer> ); }
我們可以直接調(diào)用LocationChild方法生成組件,也可以再度封裝為createComponent這樣的方法,這樣就實(shí)現(xiàn)了forwardRef中使用泛型參數(shù)的需求。
react forwardRef 導(dǎo)致 泛型丟失
網(wǎng)上沒(méi)有找到合適的方案,看了 antd 的源碼
實(shí)現(xiàn)方式如下
const ForwardTable = React.forwardRef(InternalTable) as <RecordType extends object = any>( ? props: React.PropsWithChildren<TableProps<RecordType>> & { ref?: React.Ref<HTMLDivElement> }, ) => React.ReactElement; // so u can use <Table<{id: string, b: number}> ?/>
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
react中的watch監(jiān)視屬性-useEffect介紹
這篇文章主要介紹了react中的watch監(jiān)視屬性-useEffect使用,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-09-09react使用axios進(jìn)行api網(wǎng)絡(luò)請(qǐng)求的封裝方法詳解
這篇文章主要為大家詳細(xì)介紹了react使用axios進(jìn)行api網(wǎng)絡(luò)請(qǐng)求的封裝方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來(lái)幫助2022-03-03react實(shí)現(xiàn)路由動(dòng)畫(huà)跳轉(zhuǎn)功能
這篇文章主要介紹了react路由動(dòng)畫(huà)跳轉(zhuǎn)功能,大概思路是下載第三方庫(kù)?引用,創(chuàng)建css文件引用,想要實(shí)現(xiàn)跳轉(zhuǎn)動(dòng)畫(huà)功能,就在那個(gè)組件的根節(jié)點(diǎn)綁定classname屬性即可,在跳轉(zhuǎn)的時(shí)候即可實(shí)現(xiàn),需要的朋友可以參考下2023-10-10使用React實(shí)現(xiàn)一個(gè)簡(jiǎn)單的待辦任務(wù)列表
這篇文章主要給大家介紹了使用React和Ant Design庫(kù)構(gòu)建的待辦任務(wù)列表應(yīng)用,它包含了可編輯的表格,用戶(hù)可以添加、編輯和完成任務(wù),以及保存任務(wù)列表數(shù)據(jù)到本地存儲(chǔ),文中有相關(guān)的代碼示例,需要的朋友可以參考下2023-08-08React 的調(diào)和算法Diffing 算法策略詳解
React的調(diào)和算法,主要發(fā)生在render階段,調(diào)和算法并不是一個(gè)特定的算法函數(shù),而是指在調(diào)和過(guò)程中,為提高構(gòu)建workInProcess樹(shù)的性能,以及Dom樹(shù)更新的性能,而采用的一種策略,又稱(chēng)diffing算法2021-12-12React跨端動(dòng)態(tài)化之從JS引擎到RN落地詳解
這篇文章主要為大家介紹了React跨端動(dòng)態(tài)化之從JS引擎到RN落地,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09