使用自定义TextInput和TypeScript对Native useRef进行反应



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

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

我正在转发参考,这就是应该消除警告的地方。

有什么建议吗?

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

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

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

最新更新