我有一个Block
组件,它将根据prop值呈现div
或a
标签。我想将引用从父组件传递到此组件。因此,我需要将RefForwardingComponent
type用作组件变量类型,但由于HTMLAnchorElement
和之间的类型不兼容而收到错误消息HTMLDivElement
。我该如何解决?这是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;
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>>;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句