reactjs - 为什么页面刷新按钮点击反应?
问题描述
你能告诉我为什么页面刷新按钮点击反应?我在输入字段中输入内容并按下按钮,我的页面被刷新我想获取表单字段的值 https://codesandbox.io/s/green-frost-414qi
class ContactForm extends React.Component {
handleSubmit = values => {
// print the form values to the console
console.log(values);
};
render() {
return (
<form onSubmit={this.handleSubmit}>
<div>
<label htmlFor="firstName">First Name</label>
<Field name="firstName" component="input" type="text" />
</div>
<button type="submit">Submit</button>
</form>
);
}
}
const ContactRForm = reduxForm({
// a unique name for the form
form: "contact"
})(ContactForm);
export default ContactRForm;
解决方案
这是表单在提交事件后刷新页面的标准行为。要停止这种情况,您可以添加event.preventDefault()
handleSubmit = event => {
event.preventDefault()
console.log(event.target.firstName.value); //get value from input with name of firstName
};
使用 Redux-Forms,为了获取values
对象而不刷新页面,我们必须使用 Redux-form 为我们创建的事件处理程序。它是在我们将这样的 onSubmit 属性传递给 Form 组件时创建的:
<ContactRForm onSubmit={this.submit} />
有趣的是,该处理程序现在可以通过 prop 获得handleSubmit()
,我希望它有自己的event.preventDefault()
内置。
尝试将此添加到您的表单组件代码中:
import React from "react";
import { Field, reduxForm } from "redux-form";
class ContactForm extends React.Component {
render() {
return (
<form onSubmit={this.props.handleSubmit}>
<div>
<label htmlFor="firstName">First Name</label>
<Field name="firstName" component="input" type="text" />
<label htmlFor="lastname">Last Name</label>
<Field name="lastname" component="input" type="text" />
</div>
<button type="submit">Submit</button>
</form>
);
}
}
const ContactRForm = reduxForm({
// a unique name for the form
form: "contact"
})(ContactForm);
export default ContactRForm;
现在发生与原始submit
功能相同的功能并且页面不刷新。:)
推荐阅读
- google-cloud-platform - 如何使用 Google 的 AutoML 进行 OCR
- sql - 从 Fastreport 查询将值写入 SQL 数据库
- typescript - 使用 TypeScript 的互斥类型不正确
- google-analytics - GA 测量协议跟踪事件,但不跟踪增强型电子商务购买
- javascript - 所有元素获取:带不透明度的 Sidenav 内容
- ssas - MDX 计数查询给出不正确的结果
- eclipse - 如何在 xText 中编写 [1..1] 和 [1..*] 关系
- c# - C# WCF NetPipe firewall rules
- excel - 在VBA中提取空格后的字符串
- sql - 如何在 FOR XML PATH 中的根元素上放置一个属性,并且只有根元素?