如何在ReactJS中将表单字段从一页传递到另一页?

扎因·扎希德(Zain Zahid)

Checkout.js

这是checkout.js文件。在此文件中,我返回了Checkout表单,现在我想使用Checkout表单页面的表单字段。

问题是如何获取CheckoutForm页面的表单字段,并在此页面上使用它们,即checkout.js。因为我要在数据库中提交表单数据。但是表单在另一页上,而提交按钮在另一页上,例如(checkout.js页)

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import CssBaseline from '@material-ui/core/CssBaseline';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Paper from '@material-ui/core/Paper';
import Stepper from '@material-ui/core/Stepper';
import Step from '@material-ui/core/Step';
import StepLabel from '@material-ui/core/StepLabel';
import Button from '@material-ui/core/Button';
import Link from '@material-ui/core/Link';
import Typography from '@material-ui/core/Typography';
import AddressForm from './CheckoutForm';
import PaymentForm from './PaymentForm';
import Review from './Review';



function Copyright() {
    return (
        <Typography variant="body2" color="textSecondary" align="center">
            {'Copyright © '}
            <Link color="inherit" href="https://material-ui.com/">
                Your Website
      </Link>{' '}
            {new Date().getFullYear()}
            {'.'}
        </Typography>
    );
}
const useStyles = makeStyles((theme) => ({
    appBar: {
        position: 'relative',
    },

    layout: {
        width: 'auto',
        marginLeft: theme.spacing(2),
        marginRight: theme.spacing(2),
        [theme.breakpoints.up(1000 + theme.spacing(2) * 2)]: {
            width: 1100,
            marginLeft: 'auto',
            marginRight: 'auto',

        },

    },
    paper: {
        marginTop: theme.spacing(3),
        marginBottom: theme.spacing(3),
        padding: theme.spacing(2),
        [theme.breakpoints.up(700 + theme.spacing(3) * 2)]: {
            marginTop: theme.spacing(6),
            marginBottom: theme.spacing(6),
            padding: theme.spacing(3),
            backgroundColor: 'rgb(248, 246, 244)',

        },

    },
    stepper: {
        padding: theme.spacing(5, 0, 5),
        fontWeight: 'bold',
        backgroundColor: 'rgb(248, 246, 244)',


    },
    buttons: {
        display: 'flex',
        justifyContent: 'flex-end',

    },
    button: {
        marginTop: theme.spacing(3),
        marginLeft: theme.spacing(1),
        border: "none"    
    },
}));

const steps = ['Shipping address', 'Payment details', 'Review your order'];

function getStepContent(step) {
    switch (step) {
        case 0:
            return <AddressForm/>;
        case 1:
            return <PaymentForm />;
        case 2:
            return <Review />;
        default:
            throw new Error('Unknown step');
    }
}

export default function Checkout(props) {
    const classes = useStyles();
    const [activeStep, setActiveStep] = React.useState(0);

    const handleNext = () => {
        setActiveStep(activeStep + 1);
    

    };

    const handleBack = () => {
        setActiveStep(activeStep - 1);
    };

    return (
        <React.Fragment>
            <CssBaseline />
            <AppBar position="absolute" color="default" className={classes.appBar}></AppBar>
            <main className={classes.layout}>
                <Paper className={classes.paper}>
                    <Typography component="h1" variant="h3" align="center">
                        Checkout
          </Typography>
                    <Stepper activeStep={activeStep} className={classes.stepper}>
                        {steps.map((label) => (
                            <Step key={label}>
                                <StepLabel><Typography component="h1" variant="h5" align="center">
                                    {label} </Typography></StepLabel>
                            </Step>
                        ))}
                    </Stepper>

                    <React.Fragment>
                        {activeStep === steps.length ? (
                            <React.Fragment>
                                <Typography variant="h5" gutterBottom>
                                    Thank you for your order.
                </Typography>
                                <Typography variant="subtitle1">
                                    Your order number is #2001539. We have emailed your order 
                                     confirmation, and will
                                     send you an update when your order has shipped.
                </Typography>
                            </React.Fragment>
                        ) : (
                                <React.Fragment>
                                    {getStepContent(activeStep)}
                              {    <div className={classes.buttons}>
                                        {activeStep !== 0 && (
                                            <Button variant="contained" style={{outline: 'none'}} 
                                        onClick={handleBack} className={classes.button}>
                                                Back
                                            </Button>
                                        )}
                                        <Button style={{outline: 'none'}}
                                            variant="contained"
                                            color="secondary"
                                            onClick={handleNext}
                                            className={classes.button}
                                        >
                                            {activeStep === steps.length - 1 ? 'Place order' : 'Next'}
                                        </Button>
                                    </div> }
                                </React.Fragment>
                            )}
                    </React.Fragment>
                </Paper>
                <Copyright />
            </main>
        </React.Fragment>
    );
}

CheckoutForm.js

在此文件中,我使用了我想访问checkout.js文件中的该表单字段(例如名,姓和其他字段)的表单。我怎样才能做到这一点?有什么建议?

import React from 'react';
import Grid from '@material-ui/core/Grid';
import Typography from '@material-ui/core/Typography';
import TextField from '@material-ui/core/TextField';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Checkbox from '@material-ui/core/Checkbox';
import './CheckoutForm.scss'
import Button from '@material-ui/core/Button';
import { makeStyles } from '@material-ui/core/styles';


export default function AddressForm() {
  const useStyles = makeStyles((theme) => ({
  buttons: {
    display: 'flex',
    justifyContent: 'flex-end',

},
button: {
    marginTop: theme.spacing(3),
    marginLeft: theme.spacing(1),
    border: "none"    
},
}));

const classes = useStyles();

  return (
    <React.Fragment>
      <Typography variant="h4" gutterBottom>
        Customer Information
      </Typography><br /><br />

      <Grid container fluid spacing={3} >
        <Grid item xs={12} sm={6} >
          <label for="Firstname">Firstname</label>
          <input type="text" class="form-control" id="inputFirstName" placeholder="Firstname" />

        </Grid>
        <Grid item xs={12} sm={6}>
          <label for="Lastname">Lastname</label>
          <input type="text" class="form-control" id="inputLastName" placeholder="Lastname" />

        </Grid>
        <Grid item xs={12}>
          <label for="Address">Address</label>
          <input type="text" class="form-control" id="inputAddress" placeholder="Address" />

        </Grid>
        <Grid item xs={12} sm={6}>
          <label for="City">City</label>
          <input type="text" class="form-control" id="inputCity" placeholder="City" />

        </Grid>

        <Grid item xs={12} sm={6}>
          <label for="State">State</label>

          <select id="inputState" class="form-control">
            <option>Pakistan</option>
          </select>
        </Grid>
      </Grid>
    
    </React.Fragment>
  );
}



拉斐尔·乔拉(Raphael Chaula)

这是我的建议,您将addressValues对象和changeAddressValue函数传递CheckoutForm.jsfrom checkout.js,addressValues是一个具有用户填写AddressForm中所有值的对象,即名字,姓氏,地址等checkout.js,只要用户在其中更改值,该对象就由中的状态控制AddressForm/CheckoutFormchangeAddressValue功能更新一个价值观- addressFormValues中checkout.js,这将使它容易当你提交表单checkout.js,因为所有的值将已经填充的addressFormValues状态,即const [addressFormValues, setAddressFormValues] = React.useState({});

这是我的解决方案:

CheckoutForm.js

/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
import React from 'react';
import Grid from '@material-ui/core/Grid';
import Typography from '@material-ui/core/Typography';
import TextField from '@material-ui/core/TextField';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Checkbox from '@material-ui/core/Checkbox';
import './CheckoutForm.scss';
import Button from '@material-ui/core/Button';
import { makeStyles } from '@material-ui/core/styles';

const useStyles = makeStyles((theme) => ({
  buttons: {
    display: 'flex',
    justifyContent: 'flex-end',

  },
  button: {
    marginTop: theme.spacing(3),
    marginLeft: theme.spacing(1),
    border: "none"    
  },
}));

const AddressForm = ({ addressValues, changeAddressValue }) => {

  const classes = useStyles();

  return (
    <React.Fragment>
      <Typography variant="h4" gutterBottom>
        Customer Information
      </Typography><br /><br />

      <Grid container fluid spacing={3} >
        <Grid item xs={12} sm={6} >
          <label for="Firstname">Firstname</label>
          <input type="text" class="form-control" id="inputFirstName" placeholder="Firstname"  value={addressValues.firstname} onChange={(e) => changeAddressValue('firstname', e.target.value)} />

        </Grid>
        <Grid item xs={12} sm={6}>
          <label for="Lastname">Lastname</label>
          <input type="text" class="form-control" id="inputLastName" placeholder="Lastname" value={addressValues.lastname} onChange={(e) => changeAddressValue('lastname', e.target.value)} />

        </Grid>
        <Grid item xs={12}>
          <label for="Address">Address</label>
          <input type="text" class="form-control" id="inputAddress" placeholder="Address" value={addressValues.address} onChange={(e) => changeAddressValue('address', e.target.value)} />

        </Grid>
        <Grid item xs={12} sm={6}>
          <label for="City">City</label>
          <input type="text" class="form-control" id="inputCity" placeholder="City" value={addressValues.city} onChange={(e) => changeAddressValue('city', e.target.value)} />

        </Grid>

        <Grid item xs={12} sm={6}>
          <label for="State">State</label>

          <select id="inputState" class="form-control" >
            <option>Pakistan</option>
          </select>
        </Grid>
      </Grid>
    
    </React.Fragment>
  );
};

export default AddressForm;

PaymentForm.js

import React from 'react';
import Typography from '@material-ui/core/Typography';
import Grid from '@material-ui/core/Grid';
import TextField from '@material-ui/core/TextField';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Checkbox from '@material-ui/core/Checkbox';
import { createStyles } from '@material-ui/core/styles';
import StripeCheckout from 'react-stripe-checkout';
import 'react-toastify/dist/ReactToastify.css';


const styles = createStyles({
  formControlLabel: {
    fontSize: '1.5rem',
    '& label': { fontSize: '5rem' }
  }
});

const handleToken = (token) => {

  console.log(token);
};

const PaymentForm = ({ paymentFormValues, changePaymentFormValue }) => {

  return (
    <React.Fragment>
      <Typography variant="h4" gutterBottom>
                Payment method
      </Typography><br />
      <Grid container spacing={3}>
        <Grid item xs={12}>
          <FormControlLabel
            control={<Checkbox checked={paymentFormValues['checkedA']} onChange={(e) => changePaymentFormValue('checkedA', e.target.checked)} />}
            label={<Typography style={styles.formControlLabel}>Cash on 
                 delivery</Typography>}
          />
        </Grid>
        <Grid item xs={12}>
          <StripeCheckout
            stripeKey="pk_test_51I9XPQAesAg2GfzQyVB7VgP0IbmWwgcfeFJSuCpB2kbNu60AFTbFhC7dxwje8YF4w2ILMJ6o2InB9ENczpd4dCSa00e09XoDbw"
            token={handleToken}
            amount={2 * 100}
            name="All Products"

          />
        </Grid>
      </Grid>
    </React.Fragment>
  );
};

export default PaymentForm;

Checkout.js

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import CssBaseline from '@material-ui/core/CssBaseline';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Paper from '@material-ui/core/Paper';
import Stepper from '@material-ui/core/Stepper';
import Step from '@material-ui/core/Step';
import StepLabel from '@material-ui/core/StepLabel';
import Button from '@material-ui/core/Button';
import Link from '@material-ui/core/Link';
import Typography from '@material-ui/core/Typography';
import AddressForm from './CheckoutForm';
import PaymentForm from './PaymentForm';
import Review from './Review';


const useStyles = makeStyles((theme) => ({
  appBar: {
    position: 'relative',
  },

  layout: {
    width: 'auto',
    marginLeft: theme.spacing(2),
    marginRight: theme.spacing(2),
    [theme.breakpoints.up(1000 + theme.spacing(2) * 2)]: {
      width: 1100,
      marginLeft: 'auto',
      marginRight: 'auto',

    },

  },
  paper: {
    marginTop: theme.spacing(3),
    marginBottom: theme.spacing(3),
    padding: theme.spacing(2),
    [theme.breakpoints.up(700 + theme.spacing(3) * 2)]: {
      marginTop: theme.spacing(6),
      marginBottom: theme.spacing(6),
      padding: theme.spacing(3),
      backgroundColor: 'rgb(248, 246, 244)',

    },

  },
  stepper: {
    padding: theme.spacing(5, 0, 5),
    fontWeight: 'bold',
    backgroundColor: 'rgb(248, 246, 244)',


  },
  buttons: {
    display: 'flex',
    justifyContent: 'flex-end',

  },
  button: {
    marginTop: theme.spacing(3),
    marginLeft: theme.spacing(1),
    border: "none"    
  },
}));

const steps = ['Shipping address', 'Payment details', 'Review your order'];

function Copyright() {
  return (
    <Typography variant="body2" color="textSecondary" align="center">
      {'Copyright © '}
      <Link color="inherit" href="https://material-ui.com/">
                  Your Website
      </Link>{' '}
      {new Date().getFullYear()}
      {'.'}
    </Typography>
  );
}

function getStepContent(step, formValues = null, changeFormValue = null) {
  switch (step) {
  case 0:
    return <AddressForm addressValues={formValues} changeAddressValue={changeFormValue} />;
  case 1:
    return <PaymentForm paymentFormValues={formValues} changePaymentFormValue={changeFormValue}  />;
  case 2:
    return <Review />;
  default:
    throw new Error('Unknown step');
  }
}

export default function Checkout(props) {
  const classes = useStyles();
  const [paymentFormValues, setPaymentFormValues] = React.useState({});
  const [addressFormValues, setAddressFormValues] = React.useState({});
  const [activeStep, setActiveStep] = React.useState(0);

  const handleNext = () => {
    setActiveStep(activeStep + 1);
  };

  const handleBack = () => {
    setActiveStep(activeStep - 1);
  };

  const changeAddressFormValue = (key, value) => {
    let values = { ...addressFormValues };
    values[key] = value;
    setAddressFormValues(values);
  };

  const changePaymentFormValue = (key, value) => {
    let values = { ...paymentFormValues };
    values[key] = value;
    setPaymentFormValues(values);
  };

  return (
    <React.Fragment>
      <CssBaseline />
      <AppBar position="absolute" color="default" className={classes.appBar}></AppBar>
      <main className={classes.layout}>
        <Paper className={classes.paper}>
          <Typography component="h1" variant="h3" align="center">
                        Checkout
          </Typography>
          <Stepper activeStep={activeStep} className={classes.stepper}>
            {steps.map((label) => (
              <Step key={label}>
                <StepLabel><Typography component="h1" variant="h5" align="center">
                  {label} </Typography></StepLabel>
              </Step>
            ))}
          </Stepper>

          <React.Fragment>
            {activeStep === steps.length ? (
              <React.Fragment>
                <Typography variant="h5" gutterBottom>
                                    Thank you for your order.
                </Typography>
                <Typography variant="subtitle1">
                                    Your order number is #2001539. We have emailed your order 
                                     confirmation, and will
                                     send you an update when your order has shipped.
                </Typography>
              </React.Fragment>
            ) : (
              <React.Fragment>
                {
                  activeStep === 0 ? 
                    getStepContent(activeStep, addressFormValues, changeAddressFormValue)
                    : activeStep === 1 ?  getStepContent(activeStep, paymentFormValues, changePaymentFormValue)
                      : getStepContent(activeStep)
                }
                {activeStep === 0 ? <Button onClick={() => {
                  // All the address values will be availabe in addressFormValues object for further processes
                  console.log(addressFormValues);
                }} >Submit Address</Button> : null}
                {    <div className={classes.buttons}>
                  {activeStep !== 0 && (
                    <Button variant="contained" style={{outline: 'none'}} 
                      className={classes.button}
                      onClick={handleBack}
                    >
                        Back
                    </Button>
                  )}
                  <Button style={{outline: 'none'}}
                    variant="contained"
                    color="secondary"
                    onClick={handleNext}
                    className={classes.button}
                  >
                    {activeStep === steps.length - 1 ? 'Place order' : 'Next'}
                  </Button>
                </div> }
              </React.Fragment>
            )}
          </React.Fragment>
        </Paper>
        <Copyright />
      </main>
    </React.Fragment>
  );
}

快乐黑客!

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

如何在angular js中将数据从一页传递到另一页

来自分类Dev

如何在html中将数据从一页传递到另一页?

来自分类Dev

如何在html中将值从一页传递到另一页

来自分类Dev

如何在Angular JS中将数据从一页传递到另一页

来自分类Dev

如何在iOS中将图像从一页传递到另一页

来自分类Dev

如何在python tkinter中将数据从一页传递到另一页?

来自分类Dev

如何通过onclick在javascript中将值从一页传递到另一页?

来自分类Dev

如何在Android Studio中将会话ID从一页传递到另一页?

来自分类Dev

在angular js中将数据从一页传递到另一页

来自分类Dev

在jQuery中将<table> id从一页传递到另一页

来自分类Dev

在php中将变量值从一页传递到另一页

来自分类Dev

如何使用JavaScript将表单输入和音乐从一页传递到另一页?

来自分类Dev

如何使用JavaScript将表单输入和音乐从一页传递到另一页?

来自分类Dev

如何使用FlaskApp将表单数据从一页传递到另一页

来自分类Dev

如何将数据从一页传递到另一页html

来自分类Dev

如何将数组数据从一页传递到另一页

来自分类Dev

如何将值从一页传递到另一页中的角度?

来自分类Dev

如何将 jquery 变量从一页传递到另一页?

来自分类Dev

如何在JSF中将对象从一页传递到另一页而无需编写转换器

来自分类Dev

将hiddem值从一页传递到另一页,然后在PHP,MySQL中将其删除

来自分类Dev

显示表单输入值从一页到另一页

来自分类Dev

将ASP.Net GridView从一页传递到另一页

来自分类Dev

AngularJS将值从一页传递到另一页

来自分类Dev

将URL参数从一页传递到另一页

来自分类Dev

将值从一页的ajax函数传递到另一页的ajax函数

来自分类Dev

将价值从一页传递到另一页

来自分类Dev

路由:将道具从一页传递到另一页

来自分类Dev

使用jQuery将值从一页传递到另一页

来自分类Dev

PHP cookie值未从一页传递到另一页

Related 相关文章

  1. 1

    如何在angular js中将数据从一页传递到另一页

  2. 2

    如何在html中将数据从一页传递到另一页?

  3. 3

    如何在html中将值从一页传递到另一页

  4. 4

    如何在Angular JS中将数据从一页传递到另一页

  5. 5

    如何在iOS中将图像从一页传递到另一页

  6. 6

    如何在python tkinter中将数据从一页传递到另一页?

  7. 7

    如何通过onclick在javascript中将值从一页传递到另一页?

  8. 8

    如何在Android Studio中将会话ID从一页传递到另一页?

  9. 9

    在angular js中将数据从一页传递到另一页

  10. 10

    在jQuery中将<table> id从一页传递到另一页

  11. 11

    在php中将变量值从一页传递到另一页

  12. 12

    如何使用JavaScript将表单输入和音乐从一页传递到另一页?

  13. 13

    如何使用JavaScript将表单输入和音乐从一页传递到另一页?

  14. 14

    如何使用FlaskApp将表单数据从一页传递到另一页

  15. 15

    如何将数据从一页传递到另一页html

  16. 16

    如何将数组数据从一页传递到另一页

  17. 17

    如何将值从一页传递到另一页中的角度?

  18. 18

    如何将 jquery 变量从一页传递到另一页?

  19. 19

    如何在JSF中将对象从一页传递到另一页而无需编写转换器

  20. 20

    将hiddem值从一页传递到另一页,然后在PHP,MySQL中将其删除

  21. 21

    显示表单输入值从一页到另一页

  22. 22

    将ASP.Net GridView从一页传递到另一页

  23. 23

    AngularJS将值从一页传递到另一页

  24. 24

    将URL参数从一页传递到另一页

  25. 25

    将值从一页的ajax函数传递到另一页的ajax函数

  26. 26

    将价值从一页传递到另一页

  27. 27

    路由:将道具从一页传递到另一页

  28. 28

    使用jQuery将值从一页传递到另一页

  29. 29

    PHP cookie值未从一页传递到另一页

热门标签

归档