使用 @types/react 16.8.2 和 TypeScript 3.3.1。
我直接从React 文档中提取了这个前向引用示例,并添加了几个类型参数:
const FancyButton = React.forwardRef<HTMLButtonElement>((props, ref) => (
<button ref={ref} className="FancyButton">
{props.children}
</button>
));
// You can now get a ref directly to the DOM button:
const ref = React.createRef<HTMLButtonElement>();
<FancyButton ref={ref}>Click me!</FancyButton>;
我在最后一行中收到以下错误FancyButton:
类型“
{ children: string; ref: RefObject<HTMLButtonElement>; }”不可分配给类型“IntrinsicAttributes & RefAttributes<HTMLButtonElement>”。children类型“IntrinsicAttributes & RefAttributes<HTMLButtonElement>”上不存在属性“ ” .ts(2322)
看起来 React.forwardRef 返回值的类型定义是错误的,没有正确合并 children 属性。如果我<FancyButton>自动关闭,错误就会消失。缺少此错误的搜索结果使我相信我遗漏了一些明显的东西。