javascript - 将 ref 转发到 react.FC 给出类型错误:类型'IntrinsicAttributes & Props & { children :? 反应节点}
问题描述
我在这里学习如何使用前向引用我有一个 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> }
但是,子组件声明会引发此错误:
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'.
这也是公然的广告,但我试图解决这个问题以解决下面链接的另一个问题。如果您对此问题有任何见解,也请告诉我。谢谢你。 使用 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}/>
);
})
推荐阅读
- javascript - 我需要帮助才能使用 JavaScript 获取单选按钮的名称而不是值
- css - 使用 FontAwesome Unicode 反应样式化组件
- android - 更改表后将新列的默认值设置为现有列的值
- javascript - 在 Javascript 中创建 Promise
- python - 我无法弄清楚为什么无法识别两位数
- soapui - 如何将请求响应中的多个值传递到soapui上的发布请求正文中
- javascript - 更改 vue-moment 中的持续时间文本
- html - Angular 表单验证 - 在另一行/div 中显示错误
- elasticsearch - 如何在 Kibana 中显示包含唯一字段值的多值字段
- python - 仅打印最后 2 个键的函数:字典的值对