React: Event handler method for Backspace

后端 未结 2 1906
隐瞒了意图╮
隐瞒了意图╮ 2021-02-19 06:39

I am trying to handle an event when the user presses the Backspace button.

I saw this, and I guess I can find Backspace key code using

console.log(\"Did y

相关标签:
2条回答
  • 2021-02-19 07:06

    You have to listen to the onKeyDown event to capture the delete action. Example:

    var InputDemo = React.createClass({
        getInitialState: function() {
            return {
                message: ''
            };
        },
    
        onKeyDown: function(e) {
            if (e.keyCode === 8) {
                console.log('delete');
            }
        },
    
        handleChange: function(e) {
            this.setState({
                message: e.target.value
            });
        },
    
        render: function() {
            return (
                <div>
                    <input
                        value={this.state.message}
                        onChange={this.handleChange}
                        onKeyDown={this.onKeyDown}
                    />
                </div>
            );
        }
    });
    

    Running fiddle: https://jsfiddle.net/7eu41pzz/1/

    0 讨论(0)
  • 2021-02-19 07:11

    Depending on your implementation you should use onKeyUp which should ensure the value of the input has been modified before the event is fired.

    Based on the above answer

    var InputDemo = React.createClass({
    
        getInitialState: function() {
        return {
            message: ''
        };
      },
      onKeyUp: function(e) {
        // This would have the current value after hitting backspace.
        if (e.keyCode === 8) { 
         console.log('delete');
         console.log(`Value after clearing input: "${e.target.value}"`)
         // Value after clearing input: ""
        }
      },
      onKeyDown: function(e) {
        // This would have the value set regardless of hitting backspace "test"
        if (e.keyCode === 8) { 
         console.log('delete');
         console.log(`Value after clearing input: "${e.target.value}"`)
         // Value after clearing input: "Test"
        }
      },
      handleChange: function(e) {
        this.setState({
            message: e.target.value
        });
      },
      render: function() {
        return (
           <div>
              <input
                value={this.state.message}
                onChange={this.handleChange}
                onKeyDown={this.onKeyDown}
                onKeyUp={this.onKeyUp}
              />
           </div>
        );
      }
    });
    
    0 讨论(0)
提交回复
热议问题