繁体   English   中英

React/Typescript - 使用 ref 时出现 typescript 错误 - 类型 '(instance: HTMLInputElement | null) => void' 上不存在属性 'current'

[英]React/Typescript - when using ref I get typescript error - Property 'current' does not exist on type '(instance: HTMLInputElement | null) => void'

我有一个接收 ref 道具的组件:

import React, {forwardRef, ReactElement, ReactNode, HTMLProps, useRef} from 'react'
import styles from './index.module.css'
import classNames from 'classnames'
import { IconFa } from '../icon-fa'
import { useStableId } from '../use-stable-id'

export interface Props extends HTMLProps<HTMLInputElement> {
  // An icon component to show on the left.
  icon?: ReactNode
  // A help text tooltip to show on the right.
  help?: string
  // A clear text tooltip to show on the right.
  clear?: string
  // Pass an onHelp click handler to show a help button.
  onHelp?: () => void
  // Pass an onClear click handler to show a clear button.
  onClear?: () => void
  errorMessage?: ReactNode
  label?: string
  hideLabel?: boolean
}

export const FormInput = forwardRef<HTMLInputElement, Props>(function FormInput(props, ref): ReactElement {
  const { id, icon, help, hideLabel, errorMessage, onHelp, onClear, ...rest } = props
  const stableId = useStableId()
  const inputId = id ? id : stableId

  console.log(ref.current)

  const inputClassName = classNames(
    styles.input,
    icon && styles.hasLeftIcon,
    (help || onHelp || onClear) && styles.hasRightIcon
  )

  const labelClassName = classNames(
    styles.label,
    Boolean(props.value) && styles.hasValue,
    props['aria-invalid'] && styles.hasError,
    props.className
  )

  return (
    <div className={labelClassName}>
      {!hideLabel && (
        <label className={styles.labelText} htmlFor={inputId}>
          {props.label}
          {props.required && '*'}
        </label>
      )}
      <div className="relative">
        {icon && <div className={styles.leftIcon}>{icon}</div>}
        <input
          {...rest}
          id={inputId}
          ref={ref}
          aria-invalid={props['aria-invalid']}
          aria-label={props.hideLabel ? props.label : undefined}
          className={inputClassName}
        />
        {onClear && <ClearIcon {...props} />}
        {!onClear && (help || onHelp) && <HelpIcon {...props} />}
      </div>
      {props['aria-invalid'] && <span className={styles.error}>{errorMessage}</span>}
    </div>
  )
})

function HelpIcon(props: Props) {
  if (props.onHelp) {
    return (
      <button type="button" className={styles.rightIcon} aria-label={props.help} onClick={props.onHelp}>
        <IconFa icon={['far', 'info-circle']} title={props.help} />
      </button>
    )
  }

  return (
    <div className={styles.rightIcon} title={props.help}>
      <IconFa icon={['far', 'info-circle']} />
    </div>
  )
}

function ClearIcon(props: Props) {
  return (
    <button type="button" className={styles.rightIcon} aria-label={props.clear} onClick={props.onClear}>
      <IconFa icon={['far', 'times']} title={props.clear} />
    </button>
  )
}

我想检查输入字段是否处于活动状态。 我试图这样做:

const active = document.activeElement === ref.current

但是,我收到以下错误:

Property 'current' does not exist on type '(instance: HTMLInputElement | null) => void'.

我应该如何正确使用这个 forwardedRef?

在这种情况下,组件 A(此处FormInput )通过forwardRef访问ref prop,通常将其转发到内部组件 B(此处为<input> ),但同时 A 需要为其引用 B内部功能(这里是为了测试它的重点)。

问题是,如果使用父组件 P 没有为 A 的ref prop 提供任何实际参考 object ,则 A 中的refnull 它还可能收到回调 ref表单(因此错误消息中的类型)。

对于这种情况,您实际上需要在内部管理对 B 的引用(A 中的useRef )。 然后你将它暴露给 P 与useImperativeHandle结合forwardRef ,如https://www.carlrippon.com/using-a-forwarded-ref-internally/中所述

import React, { forwardRef, useImperativeHandle, useRef } from 'react'

export const FormInput = forwardRef<HTMLInputElement, Props>(function FormInput(props, forwardedRef) {
  const ref = useRef<HTMLInputElement>(null)

  // Do something internally with the ref...
  console.log(ref.current)

  // Expose the ref externally
  useImperativeHandle<HTMLInputElement | null, HTMLInputElement | null>(
    ref,
    () => internalRef.current
  );

  return (
    <input ref={ref} />
  )
})

像这样定义ref的类型:

import React, {RefObject } from "react";

ref:
      | RefObject<HTMLInputElement>
      | ((instance: OrNull<HTMLInputElement>) => void)
      | null

暂无
暂无

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

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