Submitボタンを押す or Enterキーを押した時の振る舞いが同じになる凡例
- 入力フォームセクションを、submit時の処理関数をプロパティとして持ったFormタグでラップする。
- Formタグ内のButtonタグのtypeプロパティに、"submit"を指定。
こうすることで、クリックイベントとキーボードイベント(Enterキーを押す)を統合的にウォッチしてくれるようになる。
const onSubmit = (e) => {
// 入力フォームコンポーネントのデフォルト機能(画面のリロード)を禁止。
e.preventDefault();
// Submit時の処理
};
<Form onSubmit={onSubmit}>
<Form.Control /> //入力フォーム1
<Form.Control /> //入力フォーム2
<Button type="submit">Submit</Button> //Submitボタン。
</Form>
簡単なログインフォームで実装する
仕様
- ID、パスワードは入力必須
- React BootStrapを利用
- Submitボタンを押す or Enterキーを押す → ログインしました。という文字を表示。
ソースコード
import React from "react";
import { useState } from "react";
import { Form, Button } from "react-bootstrap";
export const EasyLogin = () => {
const [id, setId] = useState<string>("");
const [password, setPassword] = useState<string>("");
const [loginStatus, setLoginStatus] = useState<boolean>(false);
const onSubmit = (e) => {
e.preventDefault()
if (id && password) {
setLoginStatus(true);
}
};
return (
<>
<h1>
Easy Login
</h1>
<Form onSubmit={onSubmit}>
<Form.Group>
<Form.Label>ID</Form.Label>
<Form.Control
type="text"
placeholder="IDを入力"
value={id}
onChange={(e) => {setId(e.target.value)}}
/>
<Form.Label>パスワード</Form.Label>
<Form.Control
type="password"
placeholder="パスワードを入力"
value={password}
onChange={(e) => {setPassword(e.target.value)}}
/>
<Button
type="submit"
disabled={ !id || !password }
>
Submit
</Button>
</Form.Group>
</Form>
{loginStatus && <h2>ログインしました。</h2>}
</>
);
};