添加表单标签并提交常量后页面不再显示

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

在添加表单和导航元素之前,页面显示得足够好。没有错误,但反应应用程序不再显示数据

reactjs新手 有一个工作(显示正确元素和标签的良好页面) 然后我尝试将其做成一个表单,以便我可以将数据发送到后端服务器

我尝试添加

 <div style={{ display: "flex" }}>
    {/* Left-hand Navigation Panel */}
    <nav style={{ width: "200px", borderRight: "1px solid black" }}>
      <ul style={{ listStyle: "none", padding: 0 }}>
        {divLabels.map((label, index) => (
          <li key={index}>
            <a
              href={`#div-${index}`}
              style={{ textDecoration: "none", color: "black" }}
            >
              {label}
            </a>
          </li>
        ))}
      </ul>
    </nav>

   <main style={{ flex: 1, padding: "20px" }}>
      <form onSubmit={this.handleSubmit.bind(this)}>
           ....... original elements
    .......
     }
        <button type="submit">Submit</button>
      </form>
    </main>



to code below
No errors are shown but page is now blank



import React, { useState } from "react";
import { onSubmit } from "react";
import { formData } from "react";
import { setFormData } from "react";


const App = () => {
  // Form data state
  const [formData, setFormData] = useState({});

 // Configuration for the number of rows in each div
 const divsConfig = [4, 4, 4]; // Example: 1st div with 3 rows, 2nd with 3 rows, etc.

 // Div labels configuration
 const divLabels = [
  "A- HOA Amenities",
  "B- HOA fees Included",
  "C- Bath Master Includes",
];

// Div labels configuration
 const textLabels = ["Please Explain", "Other", "Other"];

 // Checkbox label configuration
const checkboxLabels = {
   "A- HOA Amenities": [
    "Club House",
    "Golf Course",
    "Greenbelt",
    "Gym/Exercise Facility",
    "Playground",
    "Pool",
    "Sauna",
    "Security Gate",
    "Spa",
    "Tennis courts",
    "Other",
  ],
  "B- HOA fees Included": [
    "Common Area Maint",
   "Common Heating",
    "Common Hot Water",
    "Earthquake Insurance",
    "Exterior Maintenance",
    "Gas",
    "Hazard Insurance",
    "Management Fee",
    "Reserves",
    "Security/Gate Fee",
    "Trash Removal",
    "Water/ Sewer",
    "None",
    "Other",
  ],
"C- Bath Master Includes": [
    "Bidet",
   "Sauna",
  "Shower Over Tub",
  "Skylight",
  "Solid Surface",
  "Split Bath",
  "Stall Shower",
  "Sunken Tub",
  "Tile",
  "Tub",
  "Tub with Jets",
  "Updated Baths",
  "Other",
  ],
// Extend as needed based on your divLabels and divsConfig
};

// Handles checkbox change
const handleCheckboxChange = (divIndex, rowOffset, colIndex) => {
const label = divLabels[divIndex];
const checkbox = checkboxLabels[label][rowOffset + colIndex];
console.log(`Checkbox changed: ${label}: ${checkbox}`);
};

 // Handles textarea change
const handleTextareaChange = (divLabel) => {
  console.log(`Textarea in ${divLabel} changed.`);

 // Handle form submission
 const handleSubmit = async (event) => {
  event.preventDefault();
  console.log(formData); // Log formData to ensure it's captured correctly
  try {
    const response = await fetch("http://localhost:80/listing", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(formData),
    });
    if (!response.ok) throw new Error("Network response was not ok.");
    const data = await response.json();
    console.log(data); // Log the server response
  } catch (error) {
    console.error("There was a problem with your fetch operation:", error);
  }
 };

 let rowOffset = 0;

 return (
  <div style={{ display: "flex" }}>
    {/* Left-hand Navigation Panel */}
    <nav style={{ width: "200px", borderRight: "1px solid black" }}>
      <ul style={{ listStyle: "none", padding: 0 }}>
        {divLabels.map((label, index) => (
          <li key={index}>
            <a
              href={`#div-${index}`}
              style={{ textDecoration: "none", color: "black" }}
            >
              {label}
            </a>
          </li>
        ))}
      </ul>
    </nav>

    {/* Main Content */}
    <main style={{ flex: 1, padding: "20px" }}>
      <form onSubmit={this.handleSubmit.bind(this)}>
        {divsConfig.map((numRows, divIndex) => (
          <div key={divIndex} style={{ marginBottom: "20px" }}>
            <h3>{divLabels[divIndex]}</h3>
            {Array.from({ length: numRows }, (_, rowIndex) => (
              <div
                key={rowIndex}
                style={{ display: "flex", marginBottom: "10px" }}
              >
                {rowIndex === numRows - 1 ? (
                  // Last row: Textarea
                  <label>
                    {`${textLabels[divIndex]}:`}
                    <textarea
                      onChange={(e) =>
                        handleTextareaChange(divLabels[divIndex])
                      }
                    />
                  </label>
                ) : (
                  // Since the labels are in a single array make the starting value for each             
                  // row 5 more than the previous
                  ((rowOffset = rowIndex * 5),
                  // Other rows: Checkboxes with labels - add code to check for undefined
                 // before added checkbox
                  Array.from({ length: 5 }, (_, colIndex) => (
                    <label key={colIndex} style={{ marginRight: "10px" }}>
                      {`${
                        checkboxLabels[divLabels[divIndex]][
                          rowOffset + colIndex
                        ]
                      }`}
                      <input
                        type="checkbox"
                        onChange={() =>
                          handleCheckboxChange(
                            divLabels[divIndex],
                            rowIndex,
                            colIndex
                          )
                        }
                      />
                    </label>
                  )))
                )}
              </div>
            ))}
          </div>
        ))}
        <button type="submit">Submit</button>
       </form>
     </main>
    </div>
   );
  };
}; 

export default App;
reactjs forms onsubmit
1个回答
0
投票

据我所知,您在

handleSubmit()
中声明了
handleTextAreaChange()
,这就是为什么我猜您尝试将
handleSubmit
称为
this.handleSubmit
,这是一种错误的方法。我刚刚将
handleSubmit()
移出
handleTextAreaChange()
并在提交表单操作调用
this
之前起飞
handleSubmit
并呈现。

© www.soinside.com 2019 - 2024. All rights reserved.