n4kz / react-native-material-textfield

Material textfield
Other
900 stars 832 forks source link

Cannot format any text into the textField using onKeyPress #155

Closed VicFrolov closed 5 years ago

VicFrolov commented 5 years ago

If I wanted to format 1234 to be 12/34, or 111222333444 to be 1111 2222 3333 4444, it'll work "fine" if I use onChangeText, however if you try to use onKeyPress to detect deletes, or other keys for specific manipulations, it does not listen, and simply continues with the keys pressed.

Example:

onKeyPress(event) {
    const { key } = event.nativeEvent;

    if (key === '1') {
      return;
    }
    // do other stuff otherwise
}

doesn't seem to trigger or listen correctly, and hitting 1, although the function returns, still somehow triggers onChangeText and enters 1 into the text input box.

Mifayo commented 5 years ago

can you post your component to see it and for delete is "Backspace"

VicFrolov commented 5 years ago

Hi @Mifayo , yes I was indeed using backspace.

In order to format the following string, e.g. 1234 5678, where every fourth digit is a space, and after 9 digits, you cannot enter anymore, I had:

import React, { Component } from 'react';
import { TextField } from 'react-native-material-textfield';

class Example extends Component {
  constructor(props) {
    state = {
      code: '',
    };

    this.onKeyPress = this.onKeyPress.bind(this);
  }

  onKeyPress(event) {
    const { key } = event.nativeEvent;
    const { code } = this.state;
    let updateCode = '';

    if (key === 'Backspace') {
      updatedCode = code.slice(0, -1).trim();
    } else {
      updatedCode = `${code}${key}`
      if (updatedCode.length === 4) {
        updatedCode += ' ';
      }
    }

    this.setState({ code: udpatedCode });
  }

  render() {
    return (
      <TextField
        label='Verification Code'
        value={this.state.code}
        onKeyPress={this.onKeyPress}
        maxLength={9}
      />
    );
  }
}

I erased my old code, but this is the gist of it, might have some unaccounted for edge cases.

1) the "maxLength" is not abided by 2) it weirdly deletes 2 spaces for backspace after it reaches the first slice/trim 3) it seems to ignore the "value" passed to TextField, and it responds to the keyboard input, regardless of what the actual state is.

n4kz commented 5 years ago

Thanks for issue and sorry for delayed reply. I'm going to implement masked input support in upcoming release.