我的react组件上有一个输入字段,显示项目的行价格(两位小数,带有千位分隔符)。我希望在组件首次呈现时显示的值采用货币格式,并在用户在字段中键入时保持货币格式。
目前我的组件中有以下代码:
var React = require('react');
import accounting from 'accounting';
MoneyInput = React.createClass({
propTypes: {
name: React.PropTypes.string.isRequired,
onChange: React.PropTypes.func.isRequired,
value: React.PropTypes.number,
error: React.PropTypes.string,
},
onChange(event) {
// get rid of any money formatting
event.target.value = accounting.unformat(event.target.value);
// pass the value on
this.props.onChange(event);
},
getValue() {
return accounting.formatNumber(this.props.value, 2)
},
render() {
return (
<div className="field">
<input type="text"
name={this.props.name}
className="form-control"
value={this.getValue()}
onChange={this.onChange} />
<div className="input">{this.props.error}</div>
</div>
);
}
});
module.exports = MoneyInput;
该代码显示格式正确的数据,但每次我输入一个值时,光标都会跳到数字的末尾。
我理解为什么会发生这种情况(我认为)并且我在这里阅读了几个与在 JavaScript 中不丢失光标位置相关的问题(例如这里和这里)。
我的问题是在 React 中处理这个问题的最佳方法是什么?
我认为理想情况下我不想将光标位置存储在状态中(例如,我希望这些是Dan Abramov 语法中的演示组件)那么还有另一种方法吗?