简体   繁体   English

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

[英]How can I pass values or fields from one page to another page in ReactJS?

How can I send the value of the checkbox to the checkout.js page?如何将复选框的值发送到 checkout.js 页面? This is the PaymentForm page.这是 PaymentForm 页面。 I tried my best but it's not working correctly.我尽力了,但它不能正常工作。 Basically, I want to use the PaymentForm fields in checkout.js page because my submit button is there.基本上,我想在 checkout.js 页面中使用 PaymentForm 字段,因为我的提交按钮在那里。

PaymentForm.js 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 = ({ PaymentForm, changePaymentForm }) => {


    const [state, setState] = React.useState({
        checkedA: false,
    });

    const handleChange = (event) => {
        setState({ ...state, [event.target.name]: event.target.checked });

    };
    return (
        <React.Fragment>
            <Typography variant="h4" gutterBottom>
                Payment method
            </Typography><br />
            <Grid container spacing={3}>
                <Grid item xs={12}>
                     <FormControlLabel
                        control={<Checkbox checked={state.checkedA} onChange={handleChange} name="checkedA"/>}
                        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结帐.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 axios from '../../axios-orders';
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, paymentValues = null, changePaymentValue = null) {
  switch (step) {
  case 0:
    return <AddressForm addressValues={formValues} changeAddressValue={changeFormValue} />;
  case 1:
    return <PaymentForm PaymentForm={paymentValues} changePaymentForm={changePaymentValue}/>;
  case 2:
    return <Review />;
  default:
    throw new Error('Unknown step');
  }
}

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

  if(paymentFormValues === true){
    setPaymentFormNewValues('Cash')
  }
  if(paymentFormValues === false){
    setPaymentFormNewValues('Online')
  }
  console.log('[paymentFormNewValues: ]', paymentFormNewValues)
  console.log('[paymentFormValues: ]', paymentFormValues)

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

    axios.post('/UserPortal/CartItems/checkout_details_check.php', {
        customer_id: localStorage.getItem('Id'),
    })
    .then((response) => {
    if(response.data === null)
    {
    axios.post('/UserPortal/CartItems/checkout_details.php', {
        customer_id: localStorage.getItem('Id'),
        firstname: addressFormValues.firstname,
        lastname: addressFormValues.lastname,
        address: addressFormValues.address,
        city: addressFormValues.city,
        state: addressFormValues.state
    })
    .then((response) => {
      console.log(response.data);
    })  
    
}
else{  
    axios.post('/UserPortal/CartItems/checkout_details_update.php', {
            customer_id: localStorage.getItem('Id'),
            firstname: addressFormValues.firstname,
            lastname: addressFormValues.lastname,
            address: addressFormValues.address,
            city: addressFormValues.city,
            state: addressFormValues.state,
            payment_method: paymentFormNewValues
        })
        .then((response) => {
        console.log(response.data);
       
        })     
    }

})
     

  };

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

  const changeAddressFormValue = (key, value) => {
    let values = { ...addressFormValues };
    values[key] = value;
    setAddressFormValues(values);
  };
   const changePaymentFormValue = (key, value) => {
    let values = { ...addressFormValues };
    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 , paymentFormValues, changePaymentFormValue) : getStepContent(activeStep)}
             
                {    <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>
  );
}

It seems you have checked the activeStep wrong.看来您检查了 activeStep 错误。

Maybe the right code must be like the following:也许正确的代码必须如下所示:

<React.Fragment>
   {activeStep !== 0 ?getStepContent(activeStep, addressFormValues, changeAddressFormValue , paymentFormValues, changePaymentFormValue) : getStepContent(activeStep)}

Do you ever consider using Context API?您是否考虑过使用上下文 API?

React Context API反应上下文 API

But also you can use create a checkboxValue with useState in Checkout.js and pass setCheckBoxValue to PaymentForm in getStepContent as prop.但您也可以在 Checkout.js 中使用 useState 创建一个 checkboxValue,并将 setCheckBoxValue 作为道具传递给 getStepContent 中的 PaymentForm。 When checkbox checked trigger setCheckBoxValue and it will trigger parent component's state (Checkbox).当复选框选中触发 setCheckBoxValue 时,它将触发父组件的 state(复选框)。

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

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