Haq*_*q.H 5 javascript typescript reactjs react-ref
我正在学习如何在这里使用前向引用,我有一个 FC,我需要在其中初始化所有引用,然后将它们传递给它的子级,以便我可以获得一些 Chartjs 图表的画布实例。然而,使用forwardRef我得到一个类型错误,说ref不是孩子的属性。
const BUIDashboard: React.FC = () => {
const chartRef = React.createRef<RefObject<HorizontalBar>>()
.
.
.
return (
<Child
ref={chartRef} <------------------- TYPE ERROR HERE
isLoading={isLoadingChild}
data={childData} />
)
}
Run Code Online (Sandbox Code Playgroud)
孩子没有错误,但它是这样设置的
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}/>
)
}
Run Code Online (Sandbox Code Playgroud)
我是否错误地为孩子定义了参数?
我认为问题可能出在这一行
const Child: React.FC<Props>
Run Code Online (Sandbox Code Playgroud)
所以我将 Props 类型更新为
type Props = {
rootProps?: DashboardCardProps
isLoading?: boolean
data?: BUIMetrics['breachBreakdownByOutcome']
} & { ref: RefObject<HorizontalBar> }
Run Code Online (Sandbox Code Playgroud)
但是,子组件声明会抛出此错误:
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'.
Run Code Online (Sandbox Code Playgroud)
这也是明目张胆的广告,但我正在尝试解决这个问题,以解决下面链接的另一个问题。如果您对这个问题有任何见解,也请告诉我。谢谢。 使用react-pdf和react-chartjs-2生成pdf
type Props = {
rootProps?: DashboardCardProps
isLoading?: boolean
data?: BUIMetrics['breachBreakdownByOutcome']
}
const Child = React.forwardRef<RefObject<HorizontalBar>,Props>(({ rootProps, isLoading, data, children }, ref) => {
return (
<HorizontalBar ref={ref}/>
);
})
Run Code Online (Sandbox Code Playgroud)