IT

Enter 키를 누른 후 onChange 이벤트를 호출하려면

lottoking 2020. 5. 31. 10:26
반응형

Enter 키를 누른 후 onChange 이벤트를 호출하려면


나는 Bootstrap을 처음 사용 하고이 문제에 봉착했습니다. 입력 필드가 있고 한 자리를 입력하자마자 from 함수 onChange가 호출되지만 정수를 입력했을 때 'Enter'를 누르면 호출됩니다. 유효성 검사 기능과 동일한 문제-너무 빨리 호출됩니다.

var inputProcent = React.CreateElement(bootstrap.Input, {type: "text",
  //bsStyle: this.validationInputFactor(),
  placeholder: this.initialFactor,
  className: "input-block-level",
  onChange: this.handleInput,
  block: true,
  addonBefore: '%',
  ref:'input',
  hasFeedback: true
});

에 따르면 문서 반응 , 당신은 같은 키보드 이벤트를 수신 할 수 onKeyPress또는 onKeyUp하지 onChange.

var Input = React.createClass({
  render: function () {
    return <input type="text" onKeyDown={this._handleKeyDown} />;
  },
  _handleKeyDown: function(e) {
    if (e.key === 'Enter') {
      console.log('do validate');
    }
  }
});

업데이트 : React.Component 사용

동일한 작업을 수행하는 React.Component를 사용하는 코드는 다음과 같습니다.

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

  render() {
    return <input type="text" onKeyDown={this._handleKeyDown} />
  }
}

여기 jsfiddle이 있습니다.


입력 필드에서 onKeyPress를 직접 사용할 수 있습니다. onChange 함수는 모든 입력 필드가 변경 될 때마다 상태 값을 변경하고 Enter를 누르면 함수 search ()를 호출합니다.

<input
    type="text"
    placeholder="Search..."
    onChange={event => {this.setState({query: event.target.value})}}
    onKeyPress={event => {
                if (event.key === 'Enter') {
                  this.search()
                }
              }}
/>

양식 제어 (입력)에 대한 초점이 일반적으로 양식 자체 (입력이 아닌) 에서 (onSubmit) 이벤트를 트리거하여 onSubmit 양식에 바인딩 할 수 있을 때 Enter를 누르 십시오 .submitthis.handleInput

또는 포커스를 제거 할 때 발생 하는 blur(onBlur) 이벤트에 바인딩 할 수 있습니다 input(예 : 포커스를 얻을 수있는 다음 요소로 이동)


당신이 사용할 수있는 event.key

function Input(props) {
  return (
    <div>
      Input
      <input type="text" onKeyPress={props.onKeyPress}/>
    </div>
  )
}

class Form extends React.Component {
  constructor(props) {
    super(props)

    this.handleKeyPress = this.handleKeyPress.bind(this)
  }

  handleKeyPress(event) {
    if (event.key === 'Enter') {
      console.log('enter key pressed')
    }
  }

  render() {
    return (
      <section>
        <Input onKeyPress={this.handleKeyPress}/>
        <Output value={this.state.output}/>
      </section>
    );
  }
}

사용자 반응, 완전성에 대한 답변입니다.

반응 버전 16.4.2

모든 키 입력에 대해 업데이트하거나 제출시에만 값을 가져 오려고합니다. 주요 이벤트를 구성 요소에 추가하면 작동하지만 공식 문서에서 권장하는 대안이 있습니다.

제어 대상 구성 요소와 제어되지 않는 구성 요소

통제

로부터 문서 도구 - 양식 및 제어 구성 요소 :

In HTML, form elements such as input, textarea, and select typically maintain their own state and update it based on user input. In React, mutable state is typically kept in the state property of components, and only updated with setState().

We can combine the two by making the React state be the “single source of truth”. Then the React component that renders a form also controls what happens in that form on subsequent user input. An input form element whose value is controlled by React in this way is called a “controlled component”.

If you use a controlled component you will have to keep the state updated for every change to the value. For this to happen, you bind an event handler to the component. In the docs' examples, usually the onChange event.

Example:

1) Bind event handler in constructor (value kept in state)

constructor(props) {
    super(props);
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
}

2) Create handler function

handleChange(event) {
    this.setState({value: event.target.value});
}

3) Create form submit function (value is taken from the state)

handleSubmit(event) {
    alert('A name was submitted: ' + this.state.value);
    event.preventDefault();
}

4) Render

<form onSubmit={this.handleSubmit}>
    <label>
      Name:
      <input type="text" value={this.state.value} onChange={this.handleChange} />
    </label>
    <input type="submit" value="Submit" />
</form>

If you use controlled components, your handleChange function will always be fired, in order to update and keep the proper state. The state will always have the updated value, and when the form is submitted, the value will be taken from the state. This might be a con if your form is very long, because you will have to create a function for every component, or write a simple one that handles every component's change of value.

Uncontrolled

From the Docs - Uncontrolled component

In most cases, we recommend using controlled components to implement forms. In a controlled component, form data is handled by a React component. The alternative is uncontrolled components, where form data is handled by the DOM itself.

To write an uncontrolled component, instead of writing an event handler for every state update, you can use a ref to get form values from the DOM.

The main difference here is that you don't use the onChange function, but rather the onSubmit of the form to get the values, and validate if neccessary.

Example:

1) Bind event handler and create ref to input in constructor (no value kept in state)

constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.input = React.createRef();
}

2) Create form submit function (value is taken from the DOM component)

handleSubmit(event) {
    alert('A name was submitted: ' + this.input.current.value);
    event.preventDefault();
}

3) Render

<form onSubmit={this.handleSubmit}>
    <label>
      Name:
      <input type="text" ref={this.input} />
    </label>
    <input type="submit" value="Submit" />
</form>

If you use uncontrolled components, there is no need to bind a handleChange function. When the form is submitted, the value will be taken from the DOM and the neccessary validations can happen at this point. No need to create any handler functions for any of the input components as well.

Your issue

Now, for your issue:

... I want it to be called when I push 'Enter when the whole number has been entered

If you want to achieve this, use an uncontrolled component. Don't create the onChange handlers if it is not necessary. The enter key will submit the form and the handleSubmit function will be fired.

Changes you need to do:

Remove the onChange call in your element

var inputProcent = React.CreateElement(bootstrap.Input, {type: "text",
    //    bsStyle: this.validationInputFactor(),
    placeholder: this.initialFactor,
    className: "input-block-level",
    // onChange: this.handleInput,
    block: true,
    addonBefore: '%',
    ref:'input',
    hasFeedback: true
});

Handle the form submit and validate your input. You need to get the value from your element in the form submit function and then validate. Make sure you create the reference to your element in the constructor.

  handleSubmit(event) {
      // Get value of input field
      let value = this.input.current.value;
      event.preventDefault();
      // Validate 'value' and submit using your own api or something
  }

Example use of an uncontrolled component:

class NameForm extends React.Component {
  constructor(props) {
    super(props);
    // bind submit function
    this.handleSubmit = this.handleSubmit.bind(this);
    // create reference to input field
    this.input = React.createRef();
  }

  handleSubmit(event) {
    // Get value of input field
    let value = this.input.current.value;
    console.log('value in input field: ' + value );
    event.preventDefault();
    // Validate 'value' and submit using your own api or something
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" ref={this.input} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

ReactDOM.render(
  <NameForm />,
  document.getElementById('root')
);

You can also write a little wrapper function like this

const onEnter = (event, callback) => event.key === 'Enter' && callback()

Then consume it on your inputs

<input 
    type="text" 
    placeholder="Title of todo" 
    onChange={e => setName(e.target.value)}
    onKeyPress={e => onEnter(e, addItem)}/>

참고URL : https://stackoverflow.com/questions/31272207/to-call-onchange-event-after-pressing-enter-key

반응형