作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这是我的表单和 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>
最佳答案
更改<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>
)
}
附注请记住,表单中不应提交表单的任何按钮都应明确具有 type="button"
.
关于reactjs - 如何在react.js中使用Enter键提交表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33211672/
我是一名优秀的程序员,十分优秀!