简体   繁体   English

接口中的 React.ref 属性

[英]React.ref prop in interface

I tried putting string as the ref but I get an warning when I try to use ref?.current我尝试将字符串作为参考,但是当我尝试使用 ref?.current 时收到警告

Property 'current' does not exist on type 'string'

What should be used for ref prop in the interface.接口中的 ref prop 应该使用什么。 I don;t know what the ref type would be upfront.我不知道 ref 类型是什么。 It could be HTMLInputElement it could be a div basically it could be any element.它可以是 HTMLInputElement 也可以是 div 基本上可以是任何元素。

interface IProps {
 name: string,
 time: number
 ref?: string
}

Ref in React is generally described by the following interface: React.Ref<HTMLInputElement> . React 中的 Ref 通常由以下接口描述: React.Ref<HTMLInputElement>

Try:尝试:

interface IProps {
 name: string,
 time: number
 ref?: React.Ref<HTMLInputElement>
}

TypeScript won't let you pass a generic (as in: not known in advance) React.Ref<HTMLElement> or React.Ref<Element> . TypeScript 不会让您传递泛型(如:事先未知) React.Ref<HTMLElement>React.Ref<Element>

You need to trick the type checker to accept your ref by using any .您需要使用any来欺骗类型检查器以接受您的 ref。

interface Props {
  name: string;
  time: number;
  ref?: React.Ref<any>;
}

Keep in mind that this solution is not entirely type-safe.请记住,此解决方案并非完全类型安全。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM