货币文本框反应原生

时间:2017-06-07 10:58:35

标签: javascript mobile react-native

我正在尝试创建一个类似

的货币输入
" $00.00"

然后当你开始输入时,它首先键入美分,然后转到美元(即首先更新右侧数字),例如

" $00.50"

reddit用户发布了这段JS代码来帮助我:https://codepen.io/benjaminreid/pen/gRbgxK?editors=0010

const FormattedInput = class extends React.Component {
  constructor(props) {
    super(props);

    this.amountChanged = this.amountChanged.bind(this);

    this.state = {
      value: 0,
    };
  }

  amountChanged(e) {
    this.setState({
      value: e.target.value,
    });
  }

  formatValue(value) {
    return accounting.formatMoney(parseFloat(value) / 100);
  }

  render() {
    return (
      <div>
        <label for="formatted">Formatted input</label>
        <input
          id="formatted"
          type="text"
          value={this.formatValue(this.state.value)}  
        />
        <label for="amount">Actual user input (type in here)</label>
        <input
          id="amount"
          type="text"
          onChange={this.amountChanged}
          value={this.state.value}
        />
      </div>
    );
  }
}

const App = () =>
  <div>
    <FormattedInput/>
  </div>
;

ReactDOM.render(
  <App/>,
  document.querySelector('#app')
);

效果很好,但您输入的输入和显示的输入位于两个不同的框中。我想知道是否有办法直接输入格式化的货币箱?

有没有人有更好的解决方案?非常感谢帮助。

1 个答案:

答案 0 :(得分:0)

我尝试编写代码以解决您的问题。从头开始构建并不是那么难。

const FormattedInput = class extends React.Component {
  constructor(props) {
    super(props);

    this.amountChanged = this.amountChanged.bind(this);

    this.state = {
      value: '',
      rawValue: '',
    };
  }

  amountChanged(e) {
    let tmpAmount = '';
    let tmpValue = e.target.value.slice(-1);
    let newRawValue = this.state.rawValue + tmpValue;

    if ( this.state.value.length > e.target.value.length) {
      this.setState({
        value: '',
        rawValue: '',
      })
    }
    else {
      if (newRawValue.length === 1) {
        tmpAmount = '0.0' + newRawValue;
      }
      else if (newRawValue.length === 2) {
        tmpAmount = '0.' + newRawValue;
      }
      else {
        let intAmount = newRawValue.slice(0, newRawValue.length - 2);
        let centAmount = newRawValue.slice(-2);

        tmpAmount = intAmount.replace(/\B(?=(\d{3})+(?!\d))/g, ",") + '.' + centAmount;

      }

      this.setState({
        value: tmpAmount,
        rawValue: newRawValue,
      });

    }
  }

  formatValue(value) {
    return accounting.formatMoney(parseFloat(value) / 100);
  }

  render() {
    return (
      <div>
        <label for="amount">Mix</label>
        <input
          id="amount"
          type="text"
          placeholder="$0.00"
          onChange={this.amountChanged}
          value={this.state.value}
          />
      </div>
    );
  }
}

const App = () =>
<div>
  <FormattedInput/>
</div>
;

ReactDOM.render(
  <App/>,
  document.querySelector('#app')
);