[英]Thousand separator for read-only input
I would like to implement a thousand space separator in a ReadOnly input type number, but when trying to do so, it doesn't seem to be working and I can only write three numbers, and then the whole thing disappears.我想在 ReadOnly 输入类型编号中实现一千个空格分隔符,但是当尝试这样做时,它似乎不起作用,我只能写三个数字,然后整个事情就消失了。
<input
type="number"
onChange={props.onInputChange}
value={props.value ? props.value : 0}
min={props.min}
max={props.max}
readOnly="readonly"
/>
export const priceFormatterSpace = (price) => {
return price.toString().replace(/\B(?=(\d{3})+(?!\d))/g, " ");
};
How can I do it?我该怎么做?
This should do the trick.这应该可以解决问题。 You have to change your input to
type="text"
and first remove non-numeric characters then format the digits.您必须将输入更改为
type="text"
并首先删除非数字字符然后格式化数字。 You can only have a limited set of characters in input fields that are type="number"
.您在
type="number"
的输入字段中只能有一组有限的字符。 Chrome only allows one period or comma per value. Chrome 只允许每个值使用一个句点或逗号。
export default function App() {
const [value, setValue] = useState("");
// Format value by the thousands. Add a comma between
const numberWithCommas = (num) => {
return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
// Remove non-numeric characters from input
const removeNonNumeric = (num) => {
return num.toString().replace(/[^0-9]/g, "");
}
// Handle user typing into the input
const handleChange = (e) => {
const inputValue = numberWithCommas(removeNonNumeric(e.target.value))
setValue(inputValue);
};
return (
<input type="text" onChange={handleChange} value={value} />
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.