首页 > 解决方案 > 使用 react-phone-input-2 作为 Ant AutoComplete 的自定义输入

问题描述

我有一个自定义电话输入组件,基于react-phone-input-2

import ReactPhoneInput from 'react-phone-input-2'

export const MyPhoneInput = (props, ref) => {

    // some business logic here ...

    return (
        <ReactPhoneInput/>
    )
}

我将它用作AutoCompleteAnt 组件的自定义输入:

import { AutoComplete } from 'antd'

const App = () => (
    <AutoComplete>
        <MyPhoneInput/>
    </AutoComplete>
)

当我尝试单击它时,出现以下错误:

TypeError:inputRef.current.focus 不是函数

正如讨论bl00mber / react-phone-input-2 中提到的——将 ref 传递给输入 #187react-phone-input-2可以通过ref.current.numberInputRef.

我通过以下方式解决了焦点问题:

import ReactPhoneInput from 'react-phone-input-2'

export const MyPhoneInput = React.forwardRef((props, ref) => {
    const inputRef = useRef()

    useImperativeHandle(ref, () => ({
        focus: () => {
            inputRef.current.numberInputRef.focus()
        },
        get value () {
            return value
        },
    }))

    // some business logic here ...

    return (
        <ReactPhoneInput
            ref={inputRef}
        />
    )
})

当我尝试输入内容时,出现错误:

TypeError:无法读取未定义的属性“值”

我被这个困住了……</p>

这是一个沙箱,演示了一个问题:

https://codesandbox.io/embed/silly-sea-lelsn?fontsize=14&hidenavigation=1&theme=dark

有任何想法吗?

标签: reactjsantdref

解决方案


推荐阅读