首页 > 解决方案 > 为什么页面刷新按钮点击反应?

问题描述

你能告诉我为什么页面刷新按钮点击反应?我在输入字段中输入内容并按下按钮,我的页面被刷新我想获取表单字段的值 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;

标签: reactjsreduxreact-reduxredux-form

解决方案


这是表单在提交事件后刷新页面的标准行为。要停止这种情况,您可以添加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功能相同的功能并且页面不刷新。:)


推荐阅读