问题
I am working in React-redux and creating a number type field. The event.target.value returns a string, since it is number type editor it must return value as number so I parse the value to number. The problem comes when I try to enter 4.5 . Firstly, when I type 4 it will get parsed into 4 (sting to number). But when the . entered the number 4. get parse into 4 , so I just failed to enter the floating point values.
let onChangeText = (value)=> { fieldProps.onChange(parseFloat(value)); }
If I parse the value in onBlur then it will work but for state management I have to work on onChange . Is there any way to parse 4. string to 4. number .
回答1:
You could store user's literal input in your state and then apply the desired logic and store the result separately in the state of a parent element?
Here is a potential approach: translating between cents and dollars in html input in React
回答2:
You can use onBlur instead of onChange. Another benefit of this approach is that you reduce the amount of Redux actions; instead of firing an action on every keypress, you fire an action when the user is finished inputting data.
This will also require using defaultValue instead of value to link your component to the data. So the component would look something like this:
<input type="number" defaultValue={this.props.value} onBlur={onChangeText} />
This means the action will only trigger when your user has finished typing input, and blurred the input element.
来源:https://stackoverflow.com/questions/39672804/failed-to-parse-4-to-4