translating between cents and dollars in html input in React
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I'm in a bit of a weird situation, I am dealing with currency in my we app. On the model side, I am saving currency as cents before sending to the server as I don't want to deal with decimal points on the server side. In the view however, I want the to display normal currency and not cents.
So, I have this input field where I take the data from dollars and change it to cents:
And when there's a change in the input value, I change it back to cents before sending it upstream:
handleUpdate: function(e) { var value = e.target.value; // changing it back from cents to dollars value = parseFloat(value) * 100; // save back to the parent component managing the prop this.props.onUserUpdate(value); }
This puts me in kind of a deadlock, there's no way for me to enter a decimal point "." Let me demonstrate :
33 in the input box --> becomes 3300 in the parent state --> goes back as 33 in component prop - all good
33.3 in the input box --> becomes 3330 in the parent state --> goes back as 33.3 in the component prop - all good
33. in the input box --> becomes 3300 in the parent state --> goes back as 33 in the component prop - this is the problem
As you can see in case #3, when the user first enters "." this doesn't translate back to the same number with "."
Since it's a controlled input, there's basically no way of writing "."
I have tried using uncontrolled element with defaultValue, but the amount prop is not ready the time the component is rendered so it's just empty
Now when the user enters "33.", you store their literal input using setState(), then call back to the parent.
handleUpdate: function(e) { var value = e.target.value this.setState({value: value}) this.props.onUserUpdate(parseFloat(value) * 100) }
If the value the parent then passes back down to the child via props hasn't changed (3300 == 3300 in this case), then componentWillReceiveProps() won't do anything.