0
2

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 3 years have passed since last update.

ReactでEnterキーが押された時の挙動を指定する

Last updated at Posted at 2021-04-05

やりたいこと

  • このようなテキストボックスに文字をいれて、Enterキーを押したときにDEPLOYボタンをクリックしたときと同じ動作になるようにしたい
  • DEPLOYボタンが押された際には、handleClickStartが呼ばれる

image.png

コード

  • formにonSubmitを指定して、サブミットが走った時の動作をhandleSubmitで指定する
    • handleSubmitが呼ばれた時に、handleClickStartを呼ぶようにする
    • event.preventDefault();はsubmit処理の規定の動作を防ぐもので、これがない場合、画面描画などの一般的な処理がこのタイミングで走る
    • handleClickStart(values)のように指定できるのは(引数としてvalues与をえなくていい)、valuesはグローバル変数というかこの関数内で使える変数になっているから
  • onClickを指定すると、2重で呼ばれることになる
    • それは、明示的に指定しているonClickの動作とsubmitの動作での2回分
  const handleSubmit = (event) => {
    handleClickStart(values)
    event.preventDefault();
  };

  return (
    <React.Fragment>
      <Title>Today</Title>
      <form className={classes.root} noValidate autoComplete="off" onSubmit={handleSubmit}>
        <TextField
          id="standard-basic"
          label="Standard"
          onChange={handleChange}
          value={values}
        />
        <ResponsiveContainer>
          <Button
            type="submit"
            variant="contained"
            color="primary"
          // onClick={() => {
          //   handleClickStart(values);
          // }}
          >
            Deploy
        </Button>
        </ResponsiveContainer>
      </form>
    </React.Fragment >
  );

参考

0
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?