使用自定义 TextInput 和 TypeScript React Native useRef

Mus*_*ill 1 typescript react-native styled-components

我的自定义输入组件收到以下警告:

'TextInput' refers to a value, but is being used as a type here. Did you mean 'typeof TextInput'?

useRef当引用它时,像这样使用:

const lastNameRef = useRef<TextInput>(null)

看起来像这样TextInput

import React, { forwardRef } from "react"
import {
  TextInput as ReactTextInput,
  TextInputProps as ReactTextInputProps,
} from "react-native"
import styled from "styled-components/native"
import {
  compose,
  space,
  SpaceProps,
  color,
  ColorProps,
  layout,
  LayoutProps,
  flexbox,
  FlexboxProps,
  border,
  BorderProps,
  position,
  PositionProps,
  background,
  BackgroundProps,
  typography,
  TypographyProps,
} from "styled-system"

export type TextInputProps = ReactTextInputProps &
  SpaceProps &
  ColorProps &
  LayoutProps &
  FlexboxProps &
  BorderProps &
  PositionProps &
  BackgroundProps &
  TypographyProps

const StyledTextInput = styled.TextInput<TextInputProps>`
  ${compose(
    space,
    color,
    layout,
    flexbox,
    border,
    position,
    background,
    typography,
  )};
`

export const TextInput = forwardRef<ReactTextInput, TextInputProps>(
  (
    {
      fontFamily = "body",
      fontWeight = "regular",
      fontSize = 1,
      color = "text",
      ...rest
    },
    ref,
  ) => {
    return (
      <StyledTextInput
        {...{ ref, fontFamily, fontWeight, fontSize, color, ...rest }}
      />
    )
  },
)

Run Code Online (Sandbox Code Playgroud)

我正在转发参考文献,这应该消除该警告。

有什么建议么?

Lin*_*ste 7

解决方案就在您的错误消息中,您需要使用typeof TextInput.

const lastNameRef = useRef<typeof TextInput>(null);
Run Code Online (Sandbox Code Playgroud)

之所以需要为组件而不是为组件,useRef<ReactTextInput>是因为一个是函数组件,另一个是类组件。在打字稿中,类既是底层类对象,又是表示该类实例的类型。所以你可以用作ReactTextInput类型。您TextInput是一个函数,因此它只是一个变量而不是类型。该变量的实际类型是一个非常长的定义,React.ForwardRefExoticComponent<ReactTextInputProps & SpaceProps<....但您不需要知道这一点。您可以使用 访问该类型typeof TextInput

  • 尝试使用它后,我认为由于“TextInput”的类型是 ForwardRef 的返回对象,因此您需要将该类型包装在“ElementRef”(从 React 导入的类型)中以提取底层元素,如下所示:“useRef” &lt;ElementRef&lt;typeof TextInput&gt;&gt;`,否则 ref.current 的类型将是 frontRef 对象的类型(诸如 `displayName` 等属性),并且不会具有诸如 `focus()` 等实际的本机元素方法 (2认同)