React:Backspace的事件处理程序方法

时间:2016-04-06 05:48:10

标签: reactjs

当用户按Backspace按钮时,我正在尝试处理事件。

我看到this,我猜,我可以使用

找到Backspace密钥代码

console.log( "Did u delete it? "+ e.keyCode);

e.keyCode的值未定义。

以下是代码:

define(["react"], (React) => {

  var TypingContainer = React.createClass({
   keypressed(e){

      console.log( "Did u delete it"+ e.keyCode);
  },

    handleChange: function(e) {

      //  if(e.keycode==8)
            console.log( "Did u delete it?  "+ e.keyCode);


    },

    render: function() {
      return(
         <div>

            <input
              className="typing-container"
              value={this.state.message}
              onChange={this.handleChange}
              onKeyPress={this.keypressed}

            />

         </div>
      );
    }
  })
  return TypingContainer;
});

更新:在onKeyPress事件中,我总是得到0。

3 个答案:

答案 0 :(得分:15)

您必须侦听onKeyDown事件以捕获删除操作。 例如:

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>;
  }
});

跑步小提琴:https://jsfiddle.net/7eu41pzz/1/

答案 1 :(得分:1)

我的方法要简单得多。您通常会有一些初始/默认状态:

import React, { useState } from 'react';

const initialState = {
  firstName: '',
  lastName: '',
  streetAddress1: '',
  streetAddress2: '',
  city: '',
  state: '',
  postCode: '',
  country: '',
  phone: '',
};

const Demo = () => {
  const [state, setState] = useState(initialState);

  const handleChange = (prop) => (e) => {
    setState({
      ...state,
      [prop]: e.target.value || e.target.checked || initialState[prop],
    });
  };

  return (
    <div>
      <label htmlFor="first-name">First Name</label>
      <br />
      <input
        id="first-name"
        value={state.firstName}
        onChange={handleChange('firstName')}
        aria-label="First Name"
      />
      <br />
      <label htmlFor="last-name">Last Name</label>
      <br />
      <input
        id="last-name"
        value={state.lastName}
        onChange={handleChange('lastName')}
        aria-label="Last Name"
      />
      <p>{`${state.firstName} ${state.lastName}`}</p>
    </div>
  );
}

export default Demo;

https://codesandbox.io/s/happy-albattani-kgmq1?file=/src/Demo.js

答案 2 :(得分:0)

根据您的实现,应使用onKeyUp,它应确保在触发事件之前已修改输入的值。

基于以上答案

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>
    );
  }
});