首页 > 解决方案 > 没有国家选择器的 react-phone-number-input

问题描述

我正在尝试使用流行的react-phone-number-input包,但是,打字稿出现各种错误,使用选项时with country一切都找到了,到目前为止我做了什么:

npm install --save react-phone-number-input
npm install --save @types/react-phone-number-input


import PhoneInput from 'react-phone-number-input'

<PhoneInput/>

但是,因为without country我们必须按照他们的网站中指出的那样做这样的事情:

import PhoneInput from 'react-phone-number-input/input'

function Example() {
  // `value` will be the parsed phone number in E.164 format.
  // Example: "+12133734253".
  const [value, setValue] = useState()
  // If `country` property is not passed
  // then "International" format is used.
  // Otherwise, "National" format is used.
  return (
    <PhoneInput
      country="US"
      value={value}
      onChange={setValue} />
  )
}

但是,问题是打字稿抱怨,而且他们似乎忘记为 `react-phone-number-input/input 提及 @types 东西

这是我得到的具体错误:

    TS7016: Could not find a declaration file for module 'react-phone-number-input/input'. 
'/home/liz/prj/node_modules/react-phone-number-input/input/index.commonjs.js' implicitly has an 'any' type.   
Try `npm install @types/react-phone-number-input-input-min` if it exists or add a new declaration (.d.ts) file containing `declare module 'react-phone-number-input/input';

我该如何解决这个问题?文档中提到的任何解决方法或安装?

标签: reactjs

解决方案


创建自定义类型声明。步骤:

  1. 创建名为“react-phone-number-input”的文件夹
  2. 创建子文件夹输入
  3. 在其中创建 index.d.ts
  4. 复制并粘贴以下代码

在这里,我只展示了根据我的要求足够的最小类型,但它足以构建:

/// <reference types="react">

declare module 'react-phone-number-input/input' {
  interface CustomPhoneInputProps {
    onChange: (value: string) => void;
    value: string;
    placeholder: string;
    className: string;
  }

  export default class PhoneInput extends React.Component<CustomPhoneInputProps, object> {}
}

推荐阅读