gpt4 book ai didi

reactjs - 如何在react.js中使用Enter键提交表单?

转载 作者:行者123 更新时间:2023-12-03 12:54:02 25 4
gpt4 key购买 nike

这是我的表单和 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com