使用react-number-format@5.2.2遇TypeScript类型错误求助
react-number-format v5.2.2 类型错误解决方法
问题描述
使用react-number-format(版本^5.2.2)时出现以下类型错误,切换为NumericFormat组件后问题未解决:
Cannot use namespace 'NumberFormat' as a type.ts(2709) JSX element type 'NumberFormat' does not have any construct or call signatures.
组件代码
import * as React from 'react'; import NumberFormat from 'react-number-format'; export function NumericInput(props: { inputRef: (instance: NumberFormat | null) => void; onChange: (event: { currentTarget: { name: string; value: string } }) => void; name: string; variant?: 'int' | 'float'; }) { const { inputRef, onChange, variant, ...other } = props; const parseMethod = variant && variant === 'int' ? parseInt : parseFloat; return ( <NumberFormat {...other} getInputRef={inputRef} onValueChange={(values) => { onChange({ currentTarget: { name: props.name, value: isNaN(parseMethod(values.value)) ? '0' : parseMethod(values.value).toFixed(2), }, }); }} maxLength={17} thousandSeparator isNumericString /> ); }
解决方案
1. 修正组件导入方式
v5+版本的react-number-format采用命名导出,默认导出是一个命名空间而非组件,需要修改导入语句:
// 原导入 import NumberFormat from 'react-number-format'; // 修改为 import { NumberFormat } from 'react-number-format';
2. 修正实例类型引用
不能直接用组件名NumberFormat作为实例类型,需要使用InstanceType<typeof NumberFormat>获取组件实例的正确类型:
// 原props类型定义 inputRef: (instance: NumberFormat | null) => void; // 修改为 inputRef: (instance: InstanceType<typeof NumberFormat> | null) => void;
修改后的完整代码:
import * as React from 'react'; import { NumberFormat } from 'react-number-format'; export function NumericInput(props: { inputRef: (instance: InstanceType<typeof NumberFormat> | null) => void; onChange: (event: { currentTarget: { name: string; value: string } }) => void; name: string; variant?: 'int' | 'float'; }) { const { inputRef, onChange, variant, ...other } = props; const parseMethod = variant && variant === 'int' ? parseInt : parseFloat; return ( <NumberFormat {...other} getInputRef={inputRef} onValueChange={(values) => { onChange({ currentTarget: { name: props.name, value: isNaN(parseMethod(values.value)) ? '0' : parseMethod(values.value).toFixed(2), }, }); }} maxLength={17} thousandSeparator isNumericString /> ); }
内容的提问来源于stack exchange,提问作者Jed
相关产品推荐
相关产品推荐

