簡體   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