0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

reactでonKeyPress Enter

Posted at

reactで、フォーカスされているinputformでenterが押されたら特定のアクションを実行したいとき。

class InputForm extends Component {
  constructor(props) {
    super(props);
    this.actionWhenPressEnter = this.actionWhenPressEnter.bind(this);
    this.enterListener = this.enterListener.bind(this);
  }

  // enterが押された時に行いたい処理
  actionWhenPressEnter() {
    console.log('pressed enter');
  }

  // enterが押されるのを待つ。
  enterListener(e) {
    if(e.key === 'Enter') {
      e.preventDefault()
      this.actionWhenPressEnter()
    } 
  }

  render() {
    return (
      <div>
        <input
          placeholder='placeholder' 
          onKeyPress={ this.enterListener }
        />
        <button onClick={this.handleClick}> add </button>
      </div>
    );
  }

}

コレダケ。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?