【问题标题】:React Native useRef with custom TextInput and TypeScript使用自定义 TextInput 和 TypeScript 反应原生 useRef
【发布时间】:2021-04-18 03:40:57
【问题描述】:

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

'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 }}
      />
    )
  },
)

我正在转发参考资料,这就是应该摆脱该警告的原因。

有什么建议吗?

【问题讨论】:

    标签: typescript react-native styled-components


    【解决方案1】:

    解决方法就在你的错误信息中,你需要使用typeof TextInput。

    const lastNameRef = useRef<typeof TextInput>(null);
    

    您需要为您的组件而不是useRef&lt;ReactTextInput&gt; 的原因是一个是函数组件,另一个是类组件。在打字稿中,一个类既是底层的类对象,也是代表该类实例的类型。所以你可以使用ReactTextInput 作为类型。您的 TextInput 是一个函数,因此它只是一个变量而不是类型。该变量的实际类型是以React.ForwardRefExoticComponent&lt;ReactTextInputProps &amp; SpaceProps&lt;.... 开头的很长的定义,但您不需要知道这一点。您可以使用typeof TextInput 访问该类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-10
      • 1970-01-01
      • 1970-01-01
      • 2021-07-29
      • 2017-02-06
      • 2015-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多