微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何将自己的定制 inputComponent JSX <input /> 添加到 react-phone-number-input PhoneInput?

如何解决如何将自己的定制 inputComponent JSX <input /> 添加到 react-phone-number-input PhoneInput?

代码遵循此描述。

react-phone-number-input 允许使用自己的标签替换其认的 <input /> JSX 标签,这特别需要类型 React.ForwardRefExoticComponent<React.InputHTMLAttributes<HTMLInputElement> & React.RefAttributes<any>> 并且需要一个 forwardRef(允许访问 <input /> {1}})。

虽然我相信我已经用 myTextInput 提供了这个,但编译器抱怨:

Property '$$typeof' is missing in type 'Element' but required in type 'ForwardRefExoticComponent<...Type 'Element' is not assignable to type 'ForwardRefExoticComponent<...

好的,myTextInput = <ForwardedInput 确实返回了一个 <input /> JSX 所以是的它是一个 React Element,因此错误消息是有道理的。但是所述标记将解析为 React.ForwardRefExoticComponent<React.InputHTMLAttributes<HTMLInputElement> & React.RefAttributes<any>> 那么我如何让编译器识别它?

感谢您的阅读。

import React,{ forwardRef,InputHTMLAttributes } from 'react';
import 'react-phone-number-input/style.css'
import PhoneInput from 'react-phone-number-input'

const ForwardedInput = forwardRef<any,InputHTMLAttributes<HTMLInputElement>>(
    (props,ref) => {
        const { onChange,value } = props;
        return (
            <input
                type="text"
                ref={ref}
                onChange={onChange}
                value={value}
            />
        );
    }
);

const MyPhoneInput = () => {

    const ref = React.createRef();
    const myTextInput = <ForwardedInput 
        onChange={() => {}}
        value="string"
        ref={ref}
    />;

    return (
        <div>
            <PhoneInput
                    placeholder="Enter phone number"
                    value={"value"}
                    inputComponent={myTextInput}
                    onChange={() => {
                        return;
                    }}
                />
        </div>
    );
};

export default MyPhoneInput;

解决方法

inputComponent={ForwardedInput}

这有效。现在我的生活非常忙碌,我没有时间详细解释,但会尽快回来。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。