【问题标题】:Set Up Custom Component Type That Using TextInput props and make it work when useRef to the component设置使用 TextInput 道具的自定义组件类型并使其在 useRef 到组件时工作
【发布时间】:2020-09-12 04:48:36
【问题描述】:

我正在创建一个自定义组件,脚本是使用 React 的 Hooks 用 TypeScript 编写的

我的组件将使用我的一些打字稿类型并将其与 TextInput 类型混合(这样我就可以访问 TextInput 道具)

这是我的自定义组件示例代码

import { Animated, Platform, TextInput, TextInputProps, View } from 'react-native'

type PropsType = TextInputProps & { //Or should I using TextInput instead of TextInputProps?
    myCustomProp?: string
}

const CustomTextField = (props: PropsType) => {
    useEffect(() => {
        return () => {
            if(props.onSubmitEditing != undefined) {
                props.onSubmitEditing()
            }
        }
    }, [])

    return (
        <View
            style = {{
            }}
        />
    )
}

export default CustomTextField

然后我将它导入到我的屏幕上并像这样显示它

<CustomTextField
    placeholder = 'Password'
    ref = {passwordInput}
    secureTextEntry
/>

这是我的参考变量

const passwordInput = useRef<typeof CustomTextField>(null)

但是当引用组件时打字稿给我错误

【问题讨论】:

    标签: typescript react-native react-hooks


    【解决方案1】:

    根据文档,您不能在函数组件上使用 ref 属性,因为它们没有实例。

    但是最近函数式组件因为 hooks 什么都流行起来了,React 引入了forwardRef

    所以你的子组件代码应该是

    export default React.forwardRef((props: CustomProps, ref) => {
      // All other existing code
    });
    

    在父组件中,

    const passwordInput = useRef<CustomTextField>(null)
    
    <CustomTextField
        placeholder='Password'
        ref={passwordInput}
        secureTextEntry
    />
    

    【讨论】:

    • 非常感谢您的回答,我最终将其更改为类组件
    • 这似乎不适合我...我收到以下错误:'CustomTextInput' refers to a value, but is being used as a type here. Did you mean 'typeof CustomTextInput'?
    猜你喜欢
    • 2022-11-17
    • 2012-04-01
    • 1970-01-01
    • 2020-07-26
    • 2023-01-03
    • 1970-01-01
    • 2019-07-03
    • 2020-12-08
    • 1970-01-01
    相关资源
    最近更新 更多