小编典典

在TypeScript中对子项使用forwardRef组件

reactjs

使用@ 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的返回值的类型定义是错误的,没有正确地合并在子道具中。如果我<FancyButton>自行关闭,错误就会消失。缺少针对该错误的搜索结果,使我相信自己缺少明显的东西。


阅读 2464

收藏
2020-07-22

共1个答案

小编典典

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>

2020-07-22