[英]How to add thousand separator to Textfield?
I've tried to add thousand separator by using react-number-format package.我尝试使用react-number-format package 添加千位分隔符。 However, I couldn't make it happen.然而,我没能做到。 I use react 18. And this what I tried:我使用反应 18。这就是我尝试过的:
function NumberFormatCustom(props) {
const { inputRef, onChange, ...other } = props;
return (
<NumericFormat
{...other}
getInputRef={inputRef}
onValueChange={(values) => {
onChange({
target: {
name: props.name,
value: values.value,
},
});
}}
thousandSeparator
/>
);
}
<TextField
required
error={loanType === "I" && totalAmount > 100000}
fullWidth
type="number"
label="Tota lAmount"
value={totalAmount}
onChange={(e) => setTotalAmount(e.target.value)}
InputProps={{
inputComponent: NumberFormatCustom,
startAdornment: (
<InputAdornment position="start">$</InputAdornment>
),
}}
/>
According to the current docs you can use react-number-format
along with MUI TextField
like this:根据当前文档,您可以像这样使用react-number-format
和MUI TextField
:
import { NumericFormat } from 'react-number-format';
import { TextField } from '@mui/material';
<NumericFormat value={12323} customInput={TextField} />;
In your case, your code can be like this:在您的情况下,您的代码可以是这样的:
import { InputAdornment, TextField } from "@mui/material";
import { useState } from "react";
import { NumericFormat } from "react-number-format";
const MyNumberComponent = () => {
const [totalAmount, setTotalAmount] = useState(52100);
const handleChange = (ev) => {
setTotalAmount(ev.floatValue);
};
const materialUiTextFieldProps = {
required: true,
error: totalAmount > 100000,
fullWidth: true,
label: "Total Amount",
InputProps: {
startAdornment: <InputAdornment position="start">$</InputAdornment>
}
};
return (
<>
<NumericFormat
value={totalAmount}
customInput={TextField}
onValueChange={handleChange}
thousandSeparator=","
decimalSeparator="."
{...materialUiTextFieldProps}
/>
binded value: {totalAmount}
</>
);
};
export default MyNumberComponent;
You can take a look at this sandbox for a live working example of this approach.您可以查看此沙箱,了解此方法的实时工作示例。
I am using this, it works well ->我正在使用它,效果很好->
export const numberWithCommas = (x: number) =>
x?.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',') || '0';
And to change it back to number:并将其改回数字:
export const numberWithoutCommas = (x: number | string, isFloat?: boolean) => {
const str = x.toString().replace(/,/g, '');
return isFloat ? parseFloat(str) : parseInt(str, 10);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.