to call onChange event after pressing Enter key

前端 未结 7 481
悲&欢浪女
悲&欢浪女 2020-12-02 05:19

I am new to Bootstrap and stuck with this problem. I have an input field and as soon as I enter just one digit, the function from onChange is called, but I want

7条回答
  •  生来不讨喜
    2020-12-02 05:48

    According to React Doc, you could listen to keyboard events, like onKeyPress or onKeyUp, not onChange.

    var Input = React.createClass({
      render: function () {
        return ;
      },
      _handleKeyDown: function(e) {
        if (e.key === 'Enter') {
          console.log('do validate');
        }
      }
    });
    

    Update: Use React.Component

    Here is the code using React.Component which does the same thing

    class Input extends React.Component {
      _handleKeyDown = (e) => {
        if (e.key === 'Enter') {
          console.log('do validate');
        }
      }
    
      render() {
        return 
      }
    }
    

    Here is the jsfiddle.

    Update 2: Use a functional component

    const Input = () => {
      const handleKeyDown = (event) => {
        if (event.key === 'Enter') {
          console.log('do validate')
        }
      }
    
      return 
    }
    

提交回复
热议问题