我在這里學(xué)習(xí)如何使用前向引用我有一個(gè) FC,我需要在其中初始化所有引用,然后將它們傳遞給它的子項(xiàng),這樣我就可以獲得一些 chartjs 圖表的畫布實(shí)例。但是使用 forwardRef 我得到一個(gè)類型錯(cuò)誤,說 ref 不是孩子的屬性。const BUIDashboard: React.FC = () => { const chartRef = React.createRef<RefObject<HorizontalBar>>()... return ( <Child ref={chartRef} <------------------- TYPE ERROR HERE isLoading={isLoadingChild} data={childData} /> )}child沒有錯(cuò)誤但是是這樣設(shè)置的type Props = { rootProps?: DashboardCardProps isLoading?: boolean data?: BUIMetrics['breachBreakdownByOutcome']}const Child: React.FC<Props> = React.forwardRef(({ rootProps, isLoading, data }, ref: RefObject<HorizontalBar>) => { return ( <HorizontalBar ref={ref}/> )}我是否錯(cuò)誤地為孩子定義了參數(shù)?我認(rèn)為問題可能出在這一行const Child: React.FC<Props>所以我將道具類型更新為type Props = { rootProps?: DashboardCardProps isLoading?: boolean data?: BUIMetrics['breachBreakdownByOutcome']} & { ref: RefObject<HorizontalBar> }但是,子組件聲明會(huì)拋出此錯(cuò)誤:TS2322: Type 'ForwardRefExoticComponent<Pick<Props, "rootProps" | "isLoading" | "data"> & RefAttributes<HorizontalBar>>' is not assignable to type 'FC<Props>'. Types of property 'defaultProps' are incompatible. Type 'Partial<Pick<Props, "rootProps" | "isLoading" | "data"> & RefAttributes<HorizontalBar>> | undefined' is not assignable to type 'Partial<Props> | undefined'. Type 'Partial<Pick<Props, "rootProps" | "isLoading" | "data"> & RefAttributes<HorizontalBar>>' is not assignable to type 'Partial<Props>'. Types of property 'ref' are incompatible. Type '((instance: HorizontalBar | null) => void) | RefObject<HorizontalBar> | null | undefined' is not assignable to type 'RefObject<HorizontalBar> | undefined'. Type 'null' is not assignable to type 'RefObject<HorizontalBar> | undefined'.這也是明目張膽的廣告,但我正試圖解決這個(gè)問題以解決下面鏈接的另一個(gè)問題。如果您對這個(gè)問題有任何見解,也請告訴我。謝謝。
轉(zhuǎn)發(fā) ref 到 react.FC 給出類型錯(cuò)誤:屬性 ref 不存在于類型
胡子哥哥
2023-03-10 15:06:30