Валюта текстовое поле реагировать родной

1

Я пытаюсь создать валютный ввод, который начинается как что-то вроде

" $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')
);

Он отлично работает, но вводимый вами ввод и ввод, который отображается, находится в двух разных ячейках. Мне было интересно, есть ли способ ввести прямо в форматированную валюту?

Есть ли у кого-нибудь лучшее решение? Помощь будет принята с благодарностью.

Теги:
react-native
mobile

1 ответ

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')
);
  • 0
    Я тестирую ваше решение, оно набирает число справа налево, однако, оно всегда печатает все цифры одинаково, зависит от первой цифры, например, если я наберу 4, оно отобразит 0.04, затем я наберу 5, и оно отображать 0,44, затем я набираю 6, и он отображается как 4,44
  • 0
    @Lucky_girl Я не могу воспроизвести вашу проблему. Вы можете попробовать решение из этой ручки .

Ещё вопросы

Сообщество Overcoder
Наверх
Меню