0

我已经用 react-final-form 设置了一个联系表。问题是我真的不明白如何仅在所有字段都有效时才允许提交表单。

现在,我的表单会获取数据,并在字段为空或电子邮件地址无效时在字段下方显示错误。

作为我的 react-final-form 的基础,我使用了来自这个沙箱的代码。onSubmit我也不太明白in<Form/>onSumbitin之间有什么区别<form>

问题1.:如何仅当所有字段都有效时才允许handleSubmit?

问题 2.:这两个 onSubmit 属性有什么区别?

这是我的代码:

import React from 'react';
import { Form, Field } from "react-final-form";

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

const onSubmit = async values => {
  await sleep(300);
  window.alert(JSON.stringify(values, 0, 2));
};

export class ContactPage extends React.Component {
  constructor(props) {
    super(props);
    this.handleSubmit=this.handleSubmit.bind(this);
  }

handleSubmit(e) {
  e.preventDefault();
  console.log(this.firstName.value);

  //Setting up values for fetch body
  const firstName = this.firstName.value;
  const email = this.email.value;
  const subject = this.subject.value;
  const message = this.message.value;

  fetch('/contact/send', {
    method:'POST',
    headers:{
      'Accept':'application/json, text/plain, */*',
      'Content-Type':'application/json'
    },
    body:JSON.stringify({
      firstName:firstName,
      email:email,
      subject:subject,
      message:message,
    }),
  })
  .then(res=>res.json())
  .then(console.log('here'))
  .then(data=>console.log(data))
  .catch(err=>console.log(err));

//Cleaning up data from form
  this.firstName.value="";
  this.email.value="";
  this.subject.value="";
  this.message.value="";
};

 render() {
    return (
      <div className="contact">
        <div className="contact__form">
          <Form
      onSubmit={onSubmit}
      validate={values => {
        const errors = {};
        if (!values.firstName) {
          errors.firstName = "Required";
        }
        if (!values.subject) {
          errors.subject = "Required";
        }
        if (!values.email) {
          errors.email = "Required";
        } else if(!values.email.match( /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/)) {
          errors.email = "Please enter a valid e-mail adress"
        }
        if (!values.message) {
          errors.message = "Required";
        }
        return errors;
      }}
      render={({ handleSubmit, submitting, values}) => (
        <form onSubmit={this.handleSubmit}>
          <Field name="firstName">
            {({ input, meta }) => (
              <div>
                <input {...input}
                  type="text"
                  placeholder="Name"
                  ref={(ref) => {this.firstName = ref}}
                />
                {meta.error && meta.touched && <span>{meta.error}</span>}
              </div>
            )}
          </Field>
          <Field name="subject">
            {({ input, meta }) => (
              <div>
                <input {...input}
                  type="text"
                  placeholder="Subject"
                  ref={(ref)=>{this.subject = ref}}
                />
                {meta.error && meta.touched && <span>{meta.error}</span>}
              </div>
            )}
          </Field>
          <Field name="email">
            {({ input, meta }) => (
              <div>
                <input {...input}
                  type="email"
                  placeholder="E-mail"
                  ref={(ref) => {this.email = ref}}
                />
                {meta.error && meta.touched && <span>{meta.error}</span>}
              </div>
            )}
          </Field>
          <Field name="message">
            {({ input, meta }) => (
              <div>
                <textarea {...input}
                  type="text"
                  placeholder="Message"
                  ref={(ref) => {this.message = ref}}
                />
                {meta.error && meta.touched && <span>{meta.error}</span>}
              </div>
            )}
          </Field>
          <div className="buttons">
            <button type="submit" disabled={submitting}>
              Submit
            </button>
          </div>
        </form>
      )}
    />
          </div>
      </div>
    );
  }
}

export default (ContactPage);
4

1 回答 1

1

您正在将您的 handleSubmit 附加在直接调用的组件上而不检查验证

您应该使用<Form>组件的 onSubmit 道具来附加您的处理程序,例如

 <Form onSubmit={this.handleSubmit}

这将作为 handleSubmit 传递给<form>组件,您可以将其用作

 <form onSubmit={this.handleSubmit}>

因此,您的表单代码将如下所示:

<Form
      onSubmit={this.handleSubmit}
      validate={values => {
        const errors = {};
        if (!values.firstName) {
          errors.firstName = "Required";
        }
        if (!values.subject) {
          errors.subject = "Required";
        }
        if (!values.email) {
          errors.email = "Required";
        } else if(!values.email.match( /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/)) {
          errors.email = "Please enter a valid e-mail adress"
        }
        if (!values.message) {
          errors.message = "Required";
        }
        return errors;
      }}
      render={({ handleSubmit, submitting, values}) => ( //handler gets passed here
        <form onSubmit={handleSubmit}> //don't use this. 
          <Field name="firstName">
            {({ input, meta }) => (
              <div>
                <input {...input}
                  type="text"
                  placeholder="Name"
                  ref={(ref) => {this.firstName = ref}}
                />
                {meta.error && meta.touched && <span>{meta.error}</span>}
              </div>
            )}
          </Field>
          <Field name="subject">
            {({ input, meta }) => (
              <div>
                <input {...input}
                  type="text"
                  placeholder="Subject"
                  ref={(ref)=>{this.subject = ref}}
                />
                {meta.error && meta.touched && <span>{meta.error}</span>}
              </div>
            )}
          </Field>
          <Field name="email">
            {({ input, meta }) => (
              <div>
                <input {...input}
                  type="email"
                  placeholder="E-mail"
                  ref={(ref) => {this.email = ref}}
                />
                {meta.error && meta.touched && <span>{meta.error}</span>}
              </div>
            )}
          </Field>
          <Field name="message">
            {({ input, meta }) => (
              <div>
                <textarea {...input}
                  type="text"
                  placeholder="Message"
                  ref={(ref) => {this.message = ref}}
                />
                {meta.error && meta.touched && <span>{meta.error}</span>}
              </div>
            )}
          </Field>
          <div className="buttons">
            <button type="submit" disabled={submitting}>
              Submit
            </button>
          </div>
        </form>
      )}
    />

handleSumit将不会收到 events 参数,它会接收表单中的所有值作为参数,因此您可以将其更改为

handleSubmit(values){
console.log(values)
//You don't need the refs now
const firstName = values.firstName;
const email = values.email;
const subject = values.subject;
const message = values.message;

}
于 2018-05-30T10:17:07.313 回答