在NextJS中提交表单数据后验证并显示成功消息

问题描述 投票:0回答:2

我希望你一切都好。试图解决这段代码时我看起来很迷失和愚蠢。因此,我的 NextJs 应用程序中有一个表单组件,我正在尝试验证表单上的 onSubmit 并显示成功或错误消息。如果您也需要,这里是代码和 CSS。

JSX 代码:

import { useRef } from "react";

export default function Form() {
  const nameRef = useRef();
  const emailRef = useRef();
  const purposeRef = useRef();
  const portfolioRef = useRef();
  const messageRef = useRef();
  const locationRef = useRef();
  const comradeRef = useRef();

  function submitHandler(event) {
    event.preventDefault();

    const enteredName = nameRef.current.value;
    const enteredEmail = emailRef.current.value;
    const enteredPurpose = purposeRef.current.value;
    const enteredPortfolio = portfolioRef.current.value;
    const enteredMessage = messageRef.current.value;
    const enteredLocation = locationRef.current.value;
    const enteredComrade = comradeRef.current.value;

    const reqBody = {
      name: enteredName,
      email: enteredEmail,
      purpose: enteredPurpose,
      portfolio: enteredPortfolio,
      message: enteredMessage,
      location: enteredLocation,
      comrade: enteredComrade,
    };

    fetch("/api/feedback", {
      method: "POST",
      body: JSON.stringify(reqBody),
      headers: {
        "Content-Type": "application/json",
      },
    })
      .then((response) => response.json())
      .then((data) => console.log(data));

    // 👇️ clear all input values in the form
    event.target.reset();
  }

  return (
    <div className={classes.divForm}>
      <form onSubmit={submitHandler}>
        <div className={classes.formInputDiv}>
          <div className={classes.label}>
            <label htmlFor="name">
              What Do We Call You?:
              <span
                style={{
                  color: "blue",
                  fontSize: "0.65rem",
                  float: "right",
                }}
              >
                *Required
              </span>
            </label>
          </div>
          <input
            required
            className={classes.input}
            type="text"
            id="name"
            name="name"
            placeholder="Enter Your Name"
            ref={nameRef}
          />
        </div>

        <div className={classes.formInputDiv}>
          <div className={classes.label}>
            <label htmlFor="email">
              Your Email Address:
              <span
                style={{
                  color: "blue",
                  fontSize: "0.65rem",
                  float: "right",
                }}
              >
                *Required
              </span>
            </label>
          </div>
          <input
            required
            className={classes.input}
            type="email"
            id="email"
            name="email"
            placeholder="Enter Your Email Address"
            ref={emailRef}
          />
        </div>

        <div className={classes.formInputDiv}>
          <div className={classes.label}>
            <label htmlFor="purpose">
              Purpose Of Contact:
              <span
                style={{
                  color: "blue",
                  fontSize: "0.65rem",
                  float: "right",
                }}
              >
                *Required
              </span>
            </label>
          </div>
          <select
            style={{
              background: "#EFF0F5",
              fontSize: "0.85rem",
              padding: "0 1rem",
              fontFamily: "'Source Sans Pro', sans-serif",
            }}
            id="purpose"
            name="purpose"
            className={classes.input}
            required
            ref={purposeRef}
          >
            <option value="General Inquiries">General Inquiries</option>
            <option value="Work / Collaboration">Work / Collaboration</option>
            <option value="Endorsement / Partnership">
              Endorsement / Partnership
            </option>
            <option value="Quotes / Pricing">Quotes / Project Plan</option>
          </select>
        </div>

        <div className={classes.formInputDiv}>
          <div className={classes.label}>
            <label htmlFor="message">
              Drop Message:
              <span
                style={{
                  color: "blue",
                  fontSize: "0.65rem",
                  float: "right",
                }}
              >
                *Required
              </span>
            </label>
          </div>
          <textarea
            className={classes.textarea}
            type="text"
            rows="5"
            cols="50"
            id="message"
            name="message"
            placeholder="Give us the full gist. Tell us Wassup!"
            required
            ref={messageRef}
          />
        </div>

        <div className={classes.formInputDiv}>
          <div className={classes.label}>
            <label htmlFor="portfolio">Link To Portfolio (Optional):</label>
          </div>
          <input
            className={classes.input}
            type="text"
            id="portfolio"
            name="portfolio"
            placeholder="Enter a link to your portoflio"
            ref={portfolioRef}
          />
        </div>

        <div className={classes.formRow}>
          <div className={classes.formColumn}>
            <div className={classes.label}>
              <label htmlFor="location">
                Your Location:
                <span
                  style={{
                    color: "blue",
                    fontSize: "0.65rem",
                    float: "right",
                  }}
                >
                  *Required
                </span>
              </label>
            </div>
            <input
              required
              className={classes.input}
              type="text"
              id="location"
              name="plocation"
              placeholder="Where Are You Based?"
              ref={locationRef}
            />
          </div>
          <div className={classes.formColumn}>
            <div className={classes.label}>
              <label htmlFor="comrade">
                Hodl A Comrade?:
                <span
                  style={{
                    color: "blue",
                    fontSize: "0.65rem",
                    float: "right",
                  }}
                >
                  *Required
                </span>
              </label>
            </div>
            <input
              required
              className={classes.input}
              type="text"
              id="comrade"
              name="comrade"
              placeholder="Enter Yes or No"
              ref={comradeRef}
            />
          </div>
        </div>

        <div className={classes.buttonDiv}>
          <button className={classes.formButton} type="submit">
            Submit
          </button>
        </div>
      </form>
    </div>
  );
}

我需要有关如何实现这一目标的帮助,我知道这没什么大不了的,但应该有人帮忙。请原谅长代码,因为这是我使用 React 和 NextJs FrameWork 的第一个主要项目。

reactjs forms next.js
2个回答
0
投票

您可能想跟踪表单错误状态:

例如:

  const nameRef = useRef();
  const emailRef = useRef();
  const purposeRef = useRef();
  const portfolioRef = useRef();
  const messageRef = useRef();
  const locationRef = useRef();
  const comradeRef = useRef();

  const [isError, setIsError] = useState(null);

  function submitHandler(event) {
    event.preventDefault();

    const enteredName = nameRef.current.value;
    const enteredEmail = emailRef.current.value;
    const enteredPurpose = purposeRef.current.value;
    const enteredPortfolio = portfolioRef.current.value;
    const enteredMessage = messageRef.current.value;
    const enteredLocation = locationRef.current.value;
    const enteredComrade = comradeRef.current.value;

    const reqBody = {
      name: enteredName,
      email: enteredEmail,
      purpose: enteredPurpose,
      portfolio: enteredPortfolio,
      message: enteredMessage,
      location: enteredLocation,
      comrade: enteredComrade,
    };

    fetch("/api/feedback", {
      method: "POST",
      body: JSON.stringify(reqBody),
      headers: {
        "Content-Type": "application/json",
      },
    })
      .then((response) => {
        console.log(response);
        setIsError(false); // <-- Here
      })
      .catch(() => setIsError(true)); // <-- and here

    // 👇️ clear all input values in the form
    event.target.reset();
  }

然后根据这是否是错误来渲染消息:

...
   <div className={classes.buttonDiv}>
      <button className={classes.formButton} type="submit">
         Submit
      </button>
   </div>
   { isError === true && (<div>Error!</div>) }
   { isError === false && (<div>Success!</div>) }
...

0
投票

作为你的第一个重大项目,你做得很好。我会说使用 react-toastify 库。它易于使用。你的代码看起来有点像这样:

import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";

... ...

fetch("/api/feedback", {
  method: "POST",

  body: JSON.stringify(reqBody),

  headers: {
"Content-Type": "application/json"
  },

})

  .then((response) => response.json())

  .then((data) => {console.log(data) ; toast.success(data.message)});
  .catch((error) => toast.error(data.message));

...

<ToastContainer />
© www.soinside.com 2019 - 2024. All rights reserved.