在TypeScript中将forwardRef组件与子代一起使用

在TypeScript中将forwardRef组件与子代一起使用

本文介绍了在TypeScript中将forwardRef组件与子代一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用@ types/react 16.8.2和TypeScript 3.3.1.

Using @types/react 16.8.2 and TypeScript 3.3.1.

我直接从反应文档中提取了此前向参考示例,并添加了一些类型参数:

I lifted this forward refs example straight from the React documentation and added a couple type parameters:

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下的最后一行中出现以下错误:

I get the following error in the last line under FancyButton:

似乎React.forwardRef的返回值的类型定义是错误的,没有正确地合并在子道具中.如果我使<FancyButton>自动关闭,错误就会消失.缺少针对该错误的搜索结果,使我相信自己缺少明显的内容.

It would seem that the type definition for React.forwardRef's return value is wrong, not merging in the children prop properly. If I make <FancyButton> self-closing, the error goes away. The lack of search results for this error leads me to believe I'm missing something obvious.

推荐答案

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

trevorsg, you need to pass the button properties:

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>

In recent versions of TS and @types/react, you can also use React.ComponentPropsWithoutRef<'button'> instead of React.HTMLProps<HTMLButtonElement>

这篇关于在TypeScript中将forwardRef组件与子代一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 12:21