next.js 使用千位分隔符的React Material UI文本字段

cidc1ykv  于 2023-04-20  发布在  React
关注(0)|答案(1)|浏览(148)

我想用$和千位分隔符来格式化我的文本字段。即,$120,000而不是120000。我得到两个警告:
1.)警告:失败的 prop 类型:prop nameForwardRef(NumericFormatCustom)中被标记为必需,但其值为undefined。at NumericFormatCustom(webpack-internal:///./src/components/TextFieldTest.js:43:26)
但是,我的名字 prop 被定义。
2.)无法分析指定的值“$120,000”,或该值超出范围。
当我在文本字段中键入一个数字时,我得到与#2相同的警告,并显示以下控制台输出。
CHANGED {formattedValue:'$6',价值:'6',floatValue:6}
如何在Material UI文本域中添加千位分隔符?

import TextField from "@mui/material/TextField";
import React, { useState, useContext } from "react";
import { PropertyContext } from "components/PropertyContext";
import NumericFormat from "react-number-format";

const NumericFormatCustom = React.forwardRef(function NumericFormatCustom(
props,
ref
) {
const { onChange, ...other } = props;

const handleValueChange = (values) => {
    console.log("CHANGED ", values);
    const rawValue = values.value;
    const strippedValue = rawValue.replace(/[$,]/g, "");
    const parsedValue = parseInt(strippedValue);
    onChange({
    target: {
        name: props.name,
        value: parsedValue,
    },
    });
};

return (
    <NumericFormat
    {...other}
    getInputRef={ref}
    onValueChange={handleValueChange}
    thousandSeparator
    isNumericString
    prefix="$"
    />
);
});

export default function TextFieldTest(props) {
const { property } = useContext(PropertyContext);

return (
    <TextField
    label="react-number-format"
    value={values.numberformat}
    onChange={handleChange}
    name="numberformat"
    id="formatted-numberformat-input"
    InputProps={{
        inputComponent: NumericFormatCustom,
    }}
    variant="standard"
    />
);
}
r55awzrz

r55awzrz1#

react-number-format文档中所述。建议使用customInput prop将Mui组件传递到NumbericFormat Package 器组件中。但您正在做相反的事情,并试图在TextField中注入NumericFormat。
这里有一个非常简单的解决方案:

import { NumericFormat } from 'react-number-format'
import InputAdornment from '@mui/material/InputAdornment'
import TextField from '@mui/material/TextField'
import { useState } from 'react'

const [value, setValue] = useState<number>()

<NumericFormat
    label="My Label"
    value={value}
    customInput={TextField}
    InputProps={{
      startAdornment: <InputAdornment position="start">$</InputAdornment>,
    }}
    allowNegative={false}
    thousandSeparator
    placeholder="0"
    onValueChange={({ value }) => setValue(Number(value))}
  />

相关问题