react.jsでEnterキーを使用してフォームを送信するにはどうすればいいですか? 質問する

react.jsでEnterキーを使用してフォームを送信するにはどうすればいいですか? 質問する

ここに私のフォームと onClick メソッドがあります。キーボードの Enter ボタンが押されたときにこのメソッドを実行したいと思います。どうすればいいでしょうか?

注意:jQuery は歓迎されません。

comment: function (e) {
  e.preventDefault();
  this.props.comment({
    comment: this.refs.text.getDOMNode().value,
    userPostId:this.refs.userPostId.getDOMNode().value,
  })
},


<form className="commentForm">
  <textarea rows="2" cols="110" placeholder="****Comment Here****" ref="text"  /><br />
  <input type="text" placeholder="userPostId" ref="userPostId" /> <br />
  <button type="button" className="btn btn-success" onClick={this.comment}>Comment</button>
</form>

ベストアンサー1

<button type="button"に変更します。<button type="submit"を削除します。onClick代わりに を実行します<form className="commentForm" onSubmit={onFormSubmit}>。 これにより、ボタンのクリックとリターンキーの押下がキャッチされるはずです。

const onFormSubmit = e => {
  e.preventDefault();
  // send state to server with e.g. `window.fetch`
}

...

<form onSubmit={onFormSubmit}>
  ...
  <button type="submit">Submit</button>
</form>

無駄なフォームライブラリを一切使用しない完全な例:

function LoginForm() {
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [submitting, setSubmitting] = useState(false)
  const [formError, setFormError] = useState('')

  const onFormSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    try {
      e.preventDefault();
      setFormError('')
      setSubmitting(true)
      await fetch(/*POST email + password*/)
    } catch (err: any) {
      console.error(err)
      setFormError(err.toString())
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <form onSubmit={onFormSubmit}>
      <input type="email" autoComplete="email" value={email} onChange={e => setEmail(e.currentTarget.value)} required />
      <input type="password" autoComplete="current-password" value={password} onChange={e => setPassword(e.currentTarget.value)} required />
      {Boolean(formError) &&
        <div className="form-error">{formError}</div>
      }
      <button type="submit" disabled={submitting}>Login</button>
    </form>
  )
}

PS フォーム内のボタンはいけないフォームを送信する場合は明示的に を指定する必要がありますtype="button"

おすすめ記事