小编典典

在React中格式化数字时停止光标跳

reactjs

我的react组件上有一个输入字段,用于显示某项的价格(两个小数位和数千个分隔符)。我希望显示的值在组件首次呈现时以money格式显示,并且还应保留为用户在字段中键入时的money格式。

目前,我的组件中包含以下代码:

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语法中的Presentation
Components
),所以还有另一种方法吗?


阅读 366

收藏
2020-07-22

共1个答案

小编典典

嗨,在github.com
https://github.com/facebook/react/issues/955上对此问题进行了讨论,参阅11月30日的评论

您可能还希望在输入组件上使用setstate。

2020-07-22