[英]Thousand separator for read-only input
我想在 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, " ");
};
我该怎么做?
这应该可以解决问题。 您必须将输入更改为type="text"
并首先删除非数字字符然后格式化数字。 您在type="number"
的输入字段中只能有一组有限的字符。 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.