如何将表单中的数据发送到 React 中的摘要页面?

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

我目前正在学习 React,我想从表单中的用户输入发送数据。我希望在新页面上收集数据。我还希望我的 getCartTotal 组件的总价显示在同一页面上。

你有什么建议给我吗?

这是我到目前为止的代码:

import React, { useContext } from "react";
import { StoreComponent } from "../../components/StoreComponents";
import { Button } from "@mui/material";
import "../../styles/Order.css";

function Order() {
  const { getCartTotal } = useContext(StoreComponent);

  return (
    <form className="place-order">
      <div className="place-order-left">
        <p className="title">Delivery information</p>
        <div className="multi-fields">
          <input type="text" placeholder="Firstname"></input>
          <input type="text" placeholder="Lastname"></input>
        </div>
        <input type="email" placeholder="E-mail"></input>
        <div className="multi-fields">
          <input type="text" placeholder="Address"></input>
        </div>
        <div className="multi-fields">
          <input type="text" placeholder="zipcode"></input>
          <input type="text" placeholder="city"></input>
        </div>
        <input type="text" placeholder="phone"></input>
      </div>
      <div className="place-order-middle">
        <p className="title">Payment</p>
        <div className="multi-fields">
          <input type="text" placeholder="cardnumber"></input>
        </div>

        <div className="multi-fields">
          <input type="text" placeholder="expired"></input>
          <input type="text" placeholder="CVC-code"></input>
        </div>
      </div>

      <div className="place-order-right">
        <div className="cart-total">
          <h2>Cart Total</h2>
          <div>
            <div className="cart-totals-details">
              <p>Sum</p>
              <p>{getCartTotal()} $</p>
            </div>
            <hr></hr>
            <div className="cart-totals-details">
              <p>Fee</p>
              <p>{getCartTotal() === 0 ? 0 : 2} $</p>
            </div>
            <hr></hr>
            <div className="cart-totals-details">
              <b>Total</b>
              <b>{getCartTotal() === 0 ? 0 : getCartTotal() + 2} $</b>
            </div>
          </div>
          <Button variant="contained">Pay now</Button>
        </div>
      </div>
    </form>
  );
}

export default Order;
html css reactjs node.js
1个回答
0
投票

我也是新人,这里给大家准备了解决方案。 但我无法使用准确的行业术语向您解释。 不过,我会根据我的理解解释正在发生的事情。

import "./App.css";
import Home from "./components/Home";
import Child from "./components/FormComponent";
import Summary from "./components/SummaryComponent";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import { useState } from "react";

function App() {


// declaring a state variable to hold the form data once the form is submitted.
//I dont think we can pass prop between two child components.
// so what we do is we pass the data to their immediate parent component 
//and then pass down from their to the next component.

  const [formData, setFormData] = useState("");

// This function is passed as prop to FormComponent,
//which then when we submit the will be called and will set the form data.

  const transferToSummaryComponent = (data) => {
    setFormData(data);
  };

  return (
    <div className="App">
      <h1>App</h1>
      <Router>
        <Routes>
          <Route path="/home" Component={Home} />
          <Route path="/child" element={<ChildComponent 
                  onSubmit={transferToSummaryComponent} />} />
              //function being passed as prop.
          <Route path="/summary" element={<SummaryComponent
                  data={childData} />} />
             //once form data is set, it is then passed as prop to needed component.
        </Routes>
      </Router>
    </div>
  );
}

export default App;



import React, { useState } from 'react'
import { useNavigate } from 'react-router-dom'

const FormComponent = (props) => {

    const navigate = useNavigate();

// to handle and hold the inputs given in forms.
    const [formData, setFormData] = useState({
        name: '',
        email: '',
        cartTotal: ''  //this is for total price or getCartTotal.
//unlike other fields, this is not being retrieved from user input.
// so we get a hold to this value a little differently. with a function below.
    })


// function to get a hold to cartTotal.
    const calculateCartTotal = () => {
        return "$500";
//this block can be replaced with your logic. For now i think it can be as:
//  const { getCartTotal } = useContext(StoreComponent);
//  return getCartTotal
// not sure this will work. but if you can somehow retireve the value,
// it will surely be passed to next component.
    };


//Just handling input but notice cartTotal is being handled slightly differently.
    const handleInput = (e) => {
        const { name, value } = e.target;
        setFormData({ ...formData, [name]: value, cartTotal: calculateCartTotal() })
    }

// handling the form submission. here, the function we passed from our
//App.js is being called "props.onSubmit(formData".
//Note: this 'onSubmit' is not related to form's onSubmit.
//If in App.js we have onWhatever={transferToSummaryComponent} instead of
//onSubmit={transferToSummaryComponent}, then it would be props.onWhatever(formData).
    const handleSubmit = (e) => {
        e.preventDefault();
        props.onSubmit(formData)    
//function passed as prop from App.js is called which take the parameter, 
//the state variable formData. Dont confuse this with formData of App.js.
//They dont relate and work in their own components.
// and when we call this function, it will go back to App.js and
//perform whatever is written in its block which for now is setFormData(formData).
//If in App.js our state variable was declared as, [receivedData, setReceivedData],
//then we would have our function as
//setReceivedData(whatever variable is declared in function defination.)

        navigate("/summary");
// this will route you to next page. And since on this Route defination, we are passing
//the receivedData(formData of App.js) as prop to the component
//we can then receive the formData in the component and work with it as needed. 
    }


    return (
        <div>
            <form onSubmit={handleSubmit}>
                <input type='text'
                       name='name'
                       value={formData.name}
                       onChange={handleInput}></input>
                <input type='text'
                       name='email'
                       value={formData.email}
                       onChange={handleInput}></input>
                <button type='submit'>Send Data</button>
            </form>
        </div>
    )
}

export default FormComponent



import React from 'react'

const SummaryComponent = ({ data }) => {    //received formData as prop.
    return (
        <div>
            <h1>Data Of Child Component</h1>   // using them as needed
            <h2>Name: {data.name}</h2>
            <h2>email: {data.email}</h2>
            <h2>Total: {data.cartTotal}</h2>
        </div>
    )
}

export default SummaryComponent
© www.soinside.com 2019 - 2024. All rights reserved.