这是我的表单和 onClick 方法。我想在按下键盘的 Enter 按钮时执行此方法。如何 ?
N.B: 没有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>
Change <button type="button"
to <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>
)
}
附:请记住,表单中的任何按钮不应该提交表单应明确具有type="button"
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)