我有一个Block
组件,它将根据prop值呈现一个div
或a
标签。我想将引用从父组件传递到此组件。因此,我需要对组件变量类型使用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;
答案 0 :(得分:3)
React.forwardedRef
希望您为无法返回的元素和道具提供类型。您可以这样表示:
import * as React from "react";
interface Props {
isLink?: boolean;
}
const Block = React.forwardRef<HTMLAnchorElement & HTMLDivElement, Props>(
({ isLink = false }, ref) => {
return isLink ? (
<a ref={ref} href="#nothing">
{"I'm a link!"}
</a>
) : (
<div ref={ref}>{"I'm a div!"}</div>
);
}
);
export default Block;
forwardRef
类型定义如下:
function forwardRef<T, P = {}>(render: ForwardRefRenderFunction<T, P>): ForwardRefExoticComponent<PropsWithoutRef<P> & RefAttributes<T>>;