Javascript 在React中html输入中转换美分和美元
我的处境有点奇怪,我在我的we应用程序中处理货币问题。在模型方面,在发送到服务器之前,我将货币保存为美分,因为我不想在服务器端处理小数点。 然而,在视图中,我希望显示正常货币,而不是美分 因此,我有一个输入字段,我从美元中获取数据,并将其更改为美分:Javascript 在React中html输入中转换美分和美元,javascript,reactjs,Javascript,Reactjs,我的处境有点奇怪,我在我的we应用程序中处理货币问题。在模型方面,在发送到服务器之前,我将货币保存为美分,因为我不想在服务器端处理小数点。 然而,在视图中,我希望显示正常货币,而不是美分 因此,我有一个输入字段,我从美元中获取数据,并将其更改为美分: <input name="balance" type="number" step="0.01" min="0" placeholder="Balance in cents" onChange={this.handleUpdate} value
<input name="balance" type="number" step="0.01" min="0" placeholder="Balance in cents" onChange={this.handleUpdate} value={this.props.user.balance / 100)} />
这让我陷入了僵局,我无法输入小数点。“让我演示一下:
33
在父状态下变为3300
-->在组件属性中变为33
,全部正常33.3
在父状态下变为3330
,在组件属性中变为33.3
,一切正常33。
在输入框中-->在父状态下变为3300
在组件属性中变为33
,这就是问题所在defaultValue
一起使用,但amount属性在渲染组件时还没有准备好,所以它只是空的
使用派生值的受控输入可能很棘手-如果您需要能够显示无效或奇怪的输入,那么
值
保持在其组件自己的状态
<input value={this.state.value} onChange={this.handleUpdate} // rest as above...
getInitialState: function() {
return {value: this.props.user.balance / 100}
}
组件将接收道具(nextProps)
以检测道具的值何时从上面更改并重新导出状态值
componentWillReceiveProps: function(nextProps) {
if (this.props.user.balance != nextProps.user.balance) {
this.setState({value: nextProps.user.balance / 100})
}
}
setState()
存储他们的文字输入,然后调用父级
handleUpdate: function(e) {
var value = e.target.value
this.setState({value: value})
this.props.onUserUpdate(parseFloat(value) * 100)
}
如果父级然后通过props传递给子级的值没有改变(3300==3300
,在这种情况下),那么componentWillReceiveProps()
不会做任何事情
工作代码段:
void函数(){'use strict';
var Parent=React.createClass({
getInitialState(){
返回{分:3300}
},
_changeValue(){
this.setState({cents:Math.round(Math.random()*2000+Math.random()*2000)})
},
_onCentsChange(美分){
this.setState({cents})
},
render(){
返回
Cents:{this.state.Cents.toFixed(0)}
}
})
var Child=React.createClass({
getInitialState(){
返回{美元:this.props.cents/100}
},
组件将接收道具(下一步){
如果(this.props.cents!=nextrops.cents){
this.setState({美元:nextrops.cents/100})
}
},
_onChange(e){
var美元=e.target.value
this.setState({dollars})
如果(!isNaN(parseFloat(美元))和&isFinite(美元)){
这个.props.onCentsChange(美元)*100)
}
},
render(){
返回
}
})
React.render(,document.querySelector('#示例'))
}()
我使用这个简单的解决方案来处理受控输入和十进制值
constructor(props) {
....
this.state = {
myProperty: 1.42,
myPropertyString: '1.42'
}
}
<input type="text"
onChange={this.handleUpdate}
value={this.state.myPropertyString}/>
很不错的!思考反应确实需要一些调整。。。谢谢你!您的示例适用于React 0.14.0,但不适用于React 15.4.2
<input type="text"
onChange={this.handleUpdate}
value={this.state.myPropertyString}/>
handleUpdate(e) {
this.setState({
myProperty: parseFloat(e.target.value),
myPropertyString: e.target.value
});
}