pre*_*ast 5 javascript rxjs reactjs react-native react-redux
晕,伙计们,我对反应还很陌生,我想提交一个只有文本区域和enter
按键的表单。我遵循了一些SO问题,但仍然没有运气,因为它没有被提交。我还想在提交后清除文本区域。我怎样才能用下面的代码做到这一点?
这是我目前拥有的代码。
const { register, handleSubmit, control, errors } = useForm();
const CommentOnSubmit = (data) => {
let formData = new FormData();
formData.append('content', data.content);
formData.append('user', user?.id);
axiosInstance.post(`api/blogs/` + slug + `/comment/`, formData);
} ;
// const commentEnterSubmit = (e) => {
// if(e.key === 'Enter' && e.shiftKey == false) {
// return(
// e.preventDefault(),
// CommentOnSubmit()
// )
// }
// }
<form noValidate onSubmit={handleSubmit(CommentOnSubmit)}>
<div className="post_comment_input">
<textarea
type="text"
placeholder="Write a comment..."
name="content"
ref={register({required: true, maxLength: 1000})}
/>
</div>
<div className="comment_post_button">
<Button type="submit" variant="contained" color="primary">comment</Button>
</div>
</form>
Run Code Online (Sandbox Code Playgroud)
请帮忙。
多谢。
你可以像这样使用React SyntheticEvent : onKeyPress
<textarea
type="text"
placeholder="Write a comment..."
onKeyPress={ commentEnterSubmit}
name="content"
ref={register({ required: true, maxLength: 1000 })}
/>
Run Code Online (Sandbox Code Playgroud)
更新
在您的commentEnterSubmit函数中:
const commentEnterSubmit = (e) => {
if (e.key === "Enter" && e.shiftKey == false) {
const data = {content:e.target.value};
return handleSubmit(CommentOnSubmit(data));
}
Run Code Online (Sandbox Code Playgroud)
如果你想重置你的输入,你可以使用setValue
fromuseForm
钩子。像这样:
添加 setValue 到 const { register, handleSubmit, control, errors,setValue } = useForm();
const CommentOnSubmit = (data) => {
let formData = new FormData();
formData.append("content", data);
formData.append("user", user?.id);
// your axios call ...
setValue("content","");
};
Run Code Online (Sandbox Code Playgroud)
我根据你的例子制作了一个代码沙箱