to call onChange event after pressing Enter key

前端 未结 7 458
悲&欢浪女
悲&欢浪女 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 06:03

    Here is a common use case using class-based components: The parent component provides a callback function, the child component renders the input box, and when the user presses Enter, we pass the user's input to the parent.

    class ParentComponent extends React.Component {
      processInput(value) {
        alert('Parent got the input: '+value);
      }
    
      render() {
        return (
          <div>
            <ChildComponent handleInput={(value) => this.processInput(value)} />
          </div>
        )
      }
    }
    
    class ChildComponent extends React.Component {
      constructor(props) {
        super(props);
        this.handleKeyDown = this.handleKeyDown.bind(this);
      }
    
      handleKeyDown(e) {
        if (e.key === 'Enter') {
          this.props.handleInput(e.target.value);
        }
      }
    
      render() {
        return (
          <div>
            <input onKeyDown={this.handleKeyDown} />
          </div>
        )
      }      
    }
    
    0 讨论(0)
提交回复
热议问题