如何解决转发ref进行反应FC给出类型错误:类型'IntrinsicAttributes&Props&{children:? ReactNode}
我正在这里学习如何使用前向引用。我有一个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} />
)
}
孩子没有任何错误,但是它是这样设置的
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}/>
)
}
我为孩子定义的参数错误吗?
我认为问题可能是这条线
const Child: React.FC<Props>
所以我将道具类型更新为
type Props = {
rootProps?: DashboardCardProps
isLoading?: boolean
data?: BUIMetrics['breachBreakdownByOutcome']
} & { ref: RefObject<HorizontalBar> }
然而,Child组件声明会引发此错误:
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'.
这也是公然的广告,但我正在设法解决此问题,以解决下面链接的另一个问题。如果您对此问题有任何见解,也请告诉我。谢谢。 Using react-pdf with react-chartjs-2 to generate a 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}/>
);
})
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。