【发布时间】:2021-04-06 08:34:29
【问题描述】:
我正在尝试编写一个 HOC 并键入您可以传递给它的孩子。
场景看起来有点像这样(也在这个沙箱中:https://codesandbox.io/s/amazing-taussig-h2dpm?file=/src/App.tsx):
interface HOCProps {
modules: React.ForwardRefExoticComponent<
HOCChildProps & React.RefAttributes<HTMLElement>
>[];
}
interface HOCChildProps {
...
}
declare const HOC: React.FC<HOCProps>;
// this produces an error in HOCTest if HTMLDivElement is used
// and an error in HOCChildTest if HTMLElement is used
// as the ref type in React.forwardRef
const HOCChildTest = React.forwardRef<HTMLDivElement, HOCChildProps>(
(props, ref) => (
<div ref={ref}>
...
</div>
)
);
const HOCTest: React.FC = () => <HOC modules={[HOCChildTest]} />;
代码仍在工作,但打字没有。
看来这个分配失败了:
declare const divTest: React.ForwardRefExoticComponent<
React.RefAttributes<HTMLDivElement>
>;
export const htmlTest: React.ForwardRefExoticComponent<
React.RefAttributes<HTMLElement>
> = divTest;
Typescript 错误信息:
Type 'ForwardRefExoticComponent<RefAttributes<HTMLDivElement>>' is not assignable to type 'ForwardRefExoticComponent<RefAttributes<HTMLElement>>'.
Types of parameters 'props' and 'props' are incompatible.
Type 'RefAttributes<HTMLElement>' is not assignable to type 'RefAttributes<HTMLDivElement>'.
在最后一行中,它指出我正在尝试将 RefAttributes<HTMLElement> 分配给 RefAttributes<HTMLDivElement>,但我以相反的方式进行分配(如第一行正确显示的那样)。
我错过了什么吗?因为我假设具有更具体 HTMLDivElement ref 的组件可以分配给具有更通用 HTMLElement ref 的组件。
【问题讨论】:
标签: reactjs typescript react-ref