I have a text field:
<Grid item xs={12} sm={6}>
<BzTextField
fullWidth
label="dec"
value={company.dex}
/>
</Grid>
what I am trying to do is to create a new component so I can create a new input type number which must add 3 decimal digits (ex. 3.3 becomes 3.300). I am having problem with how to implement something like this. Should I use Hooks or is there an easier way.
also the validation should be onChange and not on keyUp.
You can do it by creating a controlled input and using input's onBlur feature, which will execute onBlur function when you are done editing the input. This function will change add 3 decimal digits to the number.
function App() {
const [input, setInput] = React.useState("")
const onBlur = () => {
setInput(parseFloat(input).toFixed(3))
}
return (
<div >
<body>
<input
type="number"
value={input}
onChange={e=>setInput(e.target.value)}
onBlur={onBlur}
/>
</body>
</div>
);
}
Try This:
const x = 3.3;
const y = x.toFixed(3);
console.log(y);
// result 3.300
Explanation:
heretoFixed(n)
method used to extend value.
Wheren
is the number you want to extend value of number.
Here's one way you could do it using material. I made the assumption that you don't want the text formatted until focus leaves the control. The onChange event in material fires on every key press so this makes it difficult to format using that event alone.
import React, { useState } from 'react';
import { TextField } from '@material-ui/core';
const BzTextField = ({ defaultValue = '' }) => {
const [value, setValue] = useState(defaultValue);
const handleBlur = (e) => {
let parsedValue = parseFloat(e.target.value);
if (parsedValue) {
setValue(parsedValue.toFixed(3));
}
}
return (
<TextField
type="number"
fullWidth
label="dec"
value={value}
onBlur={handleBlur}/>
);
};
export default BzTextField;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.