【发布时间】:2020-06-16 07:34:01
【问题描述】:
我有一个 Block 组件,它将根据 prop 值呈现 div 或 a 标签。我想将父组件的 ref 传递给该组件。因此,我需要使用RefForwardingComponent 类型作为我的组件变量类型,但我收到HTMLAnchorElement 和HTMLDivElement 之间类型不兼容的错误。我该如何解决? here's the component code on CodeSandBox:
import * as React from "react";
interface Props {
isLink: boolean;
}
type PropsWithElementProps<T> = React.HTMLProps<T> & Props;
type RefComponent<T, U> =
| React.RefForwardingComponent<T, PropsWithElementProps<T>>
| React.RefForwardingComponent<U, PropsWithElementProps<U>>;
// error for Block variable type... full error on CodeSandBox link
const Block: RefComponent<HTMLAnchorElement, HTMLDivElement> = React.forwardRef(
({ isLink }, ref) => {
if (isLink)
return (
<a ref={ref} href="#nothing">
I'm a link!
</a>
);
else return <div ref={ref}>I'm a div!</div>;
}
);
export default Block;
【问题讨论】:
标签: reactjs typescript