use*_*513 1 reactjs redux redux-form react-redux
你能告诉我为什么在反应中点击按钮时页面刷新吗?我在输入字段中输入内容并按下按钮,我的页面正在刷新我想获取表单字段的值 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;
Run Code Online (Sandbox Code Playgroud)
表单在提交事件后刷新页面是标准行为。要停止此操作,您可以添加event.preventDefault()
handleSubmit = event => {
event.preventDefault()
console.log(event.target.firstName.value); //get value from input with name of firstName
};
Run Code Online (Sandbox Code Playgroud)
使用 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;
Run Code Online (Sandbox Code Playgroud)
现在submit出现与原始功能相同的功能并且页面不刷新。:)
| 归档时间: |
|
| 查看次数: |
3881 次 |
| 最近记录: |