使用 @types/react 16.8.2 和 TypeScript 3.3.1。
我直接从 React 文档 中提取了这个 forward refs 示例,并添加了几个类型参数:
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>
自动关闭,错误就会消失。缺少此错误的搜索结果使我相信我遗漏了一些明显的东西。
原文由 trevorsg 发布,翻译遵循 CC BY-SA 4.0 许可协议
trevorsg,您需要传递按钮属性:
添加:
在最新版本的 TS 和 @types/react 中,您还可以使用
React.ComponentPropsWithoutRef<'button'>
代替React.HTMLProps<HTMLButtonElement>