gpt4 book ai didi

reactjs - 如何处理redux表单提交的数据

转载 作者:行者123 更新时间:2023-12-02 00:52:39 24 4
gpt4 key购买 nike

我正在从 redux 表单官方页面关注本教程 http://redux-form.com/5.3.1/#/getting-started?_k=8q7qyo

我面临两个问题

1:如何在handleSubmit 函数或任何其他函数中获取表单数据。以便我可以根据需要处理表单数据。

2:每次我提交表单时,我的页面都会刷新。我不想刷新我的页面

import React, {Component} from 'react';
import {reduxForm} from 'redux-form';

class ContactForm extends Component {
render() {
const {fields: {firstName, lastName, email}, handleSubmit} = this.props;
return (
<form onSubmit={handleSubmit}>
<div>
<label>First Name</label>
<input type="text" placeholder="First Name" {...firstName}/>
</div>
<div>
<label>Last Name</label>
<input type="text" placeholder="Last Name" {...lastName}/>
</div>
<div>
<label>Email</label>
<input type="email" placeholder="Email" {...email}/>
</div>
<button type="submit">Submit</button>
</form>
);
}
}

ContactForm = reduxForm({ // <----- THIS IS THE IMPORTANT PART!
form: 'contact', // a unique name for this form
fields: ['firstName', 'lastName', 'email'] // all the fields in your form
})(ContactForm);

export default ContactForm;

已更新

最佳答案

有两种方法可以让 redux-form 在提交表单时运行一个函数:

  • 将它作为 onSubmit Prop 传递给您的装饰组件。在这种情况下,您可以在装饰组件内使用 onClick={this.props.handleSubmit} 使其在点击提交按钮时触发。
  • 将它作为参数从装饰组件内部传递给 this.props.handleSubmit 函数。在这种情况下,您可以在装饰组件内使用 onClick={this.props.handleSubmit(mySubmit)} 使其在点击提交按钮时触发。

重构示例:

import React, {Component} from 'react';
import {reduxForm} from 'redux-form';

class ContactForm extends Component {
submit(formValues) {
console.log(formValues);
}
render() {
const {fields: {firstName, lastName, email}, handleSubmit} = this.props;
return (
<form onSubmit={handleSubmit(this.submit)}>
<div>
<label>First Name</label>
<input type="text" placeholder="First Name" {...firstName}/>
</div>
<div>
<label>Last Name</label>
<input type="text" placeholder="Last Name" {...lastName}/>
</div>
<div>
<label>Email</label>
<input type="email" placeholder="Email" {...email}/>
</div>
<button type="submit">Submit</button>
</form>
);
}
}

ContactForm = reduxForm({ // <----- THIS IS THE IMPORTANT PART!
form: 'contact', // a unique name for this form
fields: ['firstName', 'lastName', 'email'] // all the fields in your form
})(ContactForm);

export default ContactForm;

来自官方文档的示例 - here

关于reactjs - 如何处理redux表单提交的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38477712/

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