简体   繁体   English

如何使用 react-router 提示用户在 React JS 中以半填形式离开页面

[英]How to use react-router to PROMPT user leaving page with a half filled form in React JS

import React from "react";
import { Formik } from "formik";
import * as Yup from "yup";
import { Button } from 'react-bootstrap';
import { Prompt } from 'react-router';

const validationSchema = Yup.object({
  name: Yup.string().required("Product Name is required"),
  quantity: Yup.number().required("Quantity is required"),
  price: Yup.number().required("Price is required"),
  manufacturer:Yup.string().required("Manufacturer details required"),
  description:Yup.string().required("Descriptopn Needed")
});

export default class ProductForm extends React.Component {
    
    render() {
      const errorStyle={"color":"red","fontWeight":"bold"}
    return (
      <Formik
        initialValues={{ name: "", quantity: ""}}
        validationSchema={validationSchema}
        validateOnChange={false}
        validateOnBlur={false}
        onSubmit={(value) => {
          var product = {};
          product.name = value.name;
          product.quantity = value.quantity;
          this.props.onAddProduct(product);
        }}
      >
        <Prompt message='You have unsaved changes, are you sure you want to leave?'/>

        {({ handleSubmit, handleChange, values, errors }) => (
          <form onSubmit={handleSubmit} style={{"margin": "0 auto","width":"30%"}}>
            <h1 style={{"display":"flex","justifyContent":"center"}}>Add Product </h1>
            <div className="form-group">
            <label for="name">Name : </label>
            <input
              type="text"
              onChange={handleChange}
              value={values.name}
              placeholer="Enter Product Name"
              name="name"
              id="name"
              className="form-control"
            />
            <span style={errorStyle}>{errors.name}</span>
            </div>
            <div className="form-group">
            <label for="quantity">Quantity : </label>
            <input
              type="number"
              onChange={handleChange}
              value={values.quantity}
              placeholer="Enter Quantity"
              name="quantity"
              id="quantity"
              className="form-control"
            />
            <span style={errorStyle}>{errors.quantity}</span>
            </div>
            <Button type="submit">Submit</Button>
          </form>
        )}
      </Formik>
    );
  }
}

I want to use REACT ROUTER in this code.我想在这段代码中使用REACT ROUTER I want the prompt to appear when the user tries to leave the page after half-filling the form.我希望当用户在半填完表单后尝试离开页面时出现提示。 I have tried to write a prompt but is confused on what the condition should be.我试图写一个提示,但对条件应该是什么感到困惑。

Also, if the user tries to REFRESH the page, the PROMPT should appear此外,如果用户尝试刷新页面,应该会出现提示

The boolean condition on when the user navigation needs to be stopped/prompted can be assigned to when prop of PROMPT like this当用户导航需要停止/提示时,boolean 条件可以分配给when PROMPT的 prop 时像这样

<Prompt
   when={shouldShowPrompt}
   message="You have unsaved changes, are you sure you want to leave?"
/>

In your case, you can set shouldShowPrompt to true when the values are empty or when the submitted values do not match the values in the input fields like this在您的情况下,当值为空或提交的值与输入字段中的值不匹配时,您可以将 shouldShowPrompt 设置为true ,如下所示

<Prompt
   when={
     !values.name ||
     !values.quantity ||
     submittedName !== values.name ||
     submittedQuantity !== values.quantity
   }
   message="You have unsaved changes, are you sure you want to leave?"
/>

Here is a working example for your code - https://codesandbox.io/s/a-simple-react-router-v4tutorial-ml5rs?file=/components/Home.js这是您的代码的工作示例 - https://codesandbox.io/s/a-simple-react-router-v4tutorial-ml5rs?file=/components/Home.js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM