I
I
Isaac Clark2015-11-20 13:22:22
JavaScript
Isaac Clark, 2015-11-20 13:22:22

Why doesn't event.preventDefault() work in React.js on onKeyUp event?

Hello.
Please tell me here is the code

<input type="text" placeholder={item.name} onKeyUp={self.checkName} />

 checkName: function (event) {
    event.preventDefault();      
    },

Why is the event.preventDefault(); does not work, that is, I both printed and print, and if I change keyUp , for example, to keyDown, then it’s normal, I can’t enter characters.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Super User, 2015-11-20
@sergeystepanov1988

You answered your own question.
But in general:

keyup
Fires when the user releases a key, after the default action of that key has been performed.

That is, the keyup event occurs when the user releases a key after the default action of that key has occurred.
Source: www.quirksmode.org/dom/events/keys.html

N
Nikita Gushchin, 2015-11-20
@iNikNik

But how then to make it so that if the user enters a value into the string that does not match the regular expression, the event.preventDefault() function is executed? because keyDown and keyPress are not suitable for this, since they take the old values

Your approach is fundamentally wrong. Your input is in the uncontrolled state. And you need to do this instead:
handleChangeSomeValue(e) {
    const nextVal = e.currentTarget.value;
    if (!isValid(nextVal)) {
      return;
    }
    this.setState({ someValue: nextVal });
  }

Working example -> jsfiddle.net/yuvuyrhv/20
Well, read the documentation -> https://facebook.github.io/react/docs/forms.html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question