使用@types/react 16.8.2和TypeScript 3.3.1.

我直接从React documentation中提取了这个正向参考示例,并添加了几个类型参数:

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>; }"不是

这似乎是React的类型定义.forwardRef的返回值错误,无法正确合并到子属性中.如果我自动关闭<FancyButton>次,错误就会消失.这个错误没有搜索结果,这让我觉得我遗漏了一些明显的东西.

推荐答案

trevorsg,你需要传递按钮属性:

import * as React from 'react'

type ButtonProps = React.HTMLProps<HTMLButtonElement>

const FancyButton = React.forwardRef<HTMLButtonElement, ButtonProps>((props, ref) => (
  <button type="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>

补充:

在TS和@types/react的最新版本中,也可以使用React.ComponentPropsWithoutRef<'button'>而不是React.HTMLProps<HTMLButtonElement>

Typescript相关问答推荐

返回签名与其他类型正确的函数不同的函数

具有条件通用props 的react 类型脚本组件错误地推断类型

Tailwind CSS样式不在Svelte应用程序中呈现

更新:Typescript实用程序函数合并对象键路径

类型断言添加到类型而不是替换

如何使类型只能有来自另一个类型的键,但键可以有一个新值,新键应该抛出一个错误

如何用不同的键值初始化角react 形式

在TypeScrip中分配回调时,参数的分配方向与回调本身相反.为什么会这样呢?

类型脚本基于数组作为泛型参数展开类型

匿名静态类推断组成不正确推断

适当限制泛型函数中的记录

对未到达受保护路由的路由环境做出react

正交摄影机正在将渲染的场景切成两半

使用TypeScrip的类型继承

从子类集合实例化类,同时保持对Typescript中静态成员的访问

如何缩小函数的返回类型?

是否可以通过映射类型将函数参数约束为预定义类型?

将布尔值附加到每个对象特性

在TypeScript中,如何通过一系列过滤器缩小类型?

React中的效果挂钩在依赖项更新后不会重新执行