尝试计算 table 行 react.js 中的值

Trying to Calculate value in table row react.js

我在这里建立了一个 table,用户可以在其中的第一个三列中输入值,然后自动填充接下来的 4 个值。我能够通过计算生成第一个两个值,但坚持使用接下来的两个列。您可以在 handleFormSubmit 函数中看到粘度和剪切率的公式。 Absolute Drop 的公式高于行粘度减去当前行,这就是为什么第一行的 Absolute Drop 将为空而第二行将为第一行的粘度减去第二行的粘度等等。 %Drop 的公式类似于((第一行的粘度减去第二行的粘度)* 100)/第一行的粘度。

import { useState } from "react";
import Table from "react-bootstrap/Table";
import './App.css'

const App = () => {
  const row1 = [];
  const [row, setRow] = useState();
  const [NewRow, setNewRow] = useState([]);
  const [NewRow2, setNewRow2] = useState([0,1,2,3,4]);
  const [allRowsAdded, updateAllRows] = useState(0);
  const [viscosity, setViscosity] = useState([]);

  const [IntensificationRatio, setIntensificationRatio] = useState()
  const [editFormData, setEditFormData] = useState({
    Injection_Speed: "",
    Fill_Time: "",
    Peak_Inj_Press: "",
    Viscosity: "",
    Shear_Rate: "",
    Absolute_Drop_Viscosity: ""
  })
  const [isRowId, setIsRowId] = useState(null)

  const handleEditFormChange = (event) => {
    event.preventDefault();

    const fieldName = event.target.getAttribute("name");
    const fieldValue = event.target.value;

    const newFormData = { ...editFormData };
    newFormData[fieldName] = fieldValue;

    setEditFormData(newFormData);
  }

  const handleEditFormSubmit = (event) => {
      event.preventDefault();

      const editedValue = {
        id: isRowId,
        Injection_Speed: editFormData.Injection_Speed,
        Fill_Time: editFormData.Fill_Time,
        Peak_Inj_Press: editFormData.Peak_Inj_Press,
        Viscosity: editFormData.Fill_Time * editFormData.Peak_Inj_Press * IntensificationRatio,
        Shear_Rate: 1 / editFormData.Fill_Time
      }

      const newValues = [...NewRow2];

      const index = NewRow2.findIndex((value) => value === isRowId)

      newValues[index] = editedValue;
      
      setNewRow2(newValues);
  }

  const addRow = (e) => {
    e.preventDefault();
    setRow(e.target.value);
  };

  const increaseRow = () => {
    for (let i = 0; i < parseInt(row); i++) {
      row1[i] = allRowsAdded + i;
    }
    updateAllRows((allRowsAdded) => allRowsAdded + parseInt(row));
    setNewRow([...NewRow, ...row1]);

  };

  const deleteRow = (id) => {
    const updatedRows = [...NewRow].filter((rowId) => {
      return rowId !== id;
    });
    setNewRow(updatedRows);
  };

  const deleteRow2 = (id) => {
    const updatedRows = [...NewRow2].filter((rowId) => {
      return rowId !== id;
    });
    setNewRow2(updatedRows);
  };

  const demo = (id) => {
    setIsRowId(id)
  }

  return (
    <>
      <div>
        <form>
          <input type="text" onChange={addRow} placeholder="Enter Number Of Row's" /><br />
          <input type="text" onChange={(e) => setIntensificationRatio(e.target.value)} placeholder="Enter Intensification Ratio" />
        </form>
        <button onClick={increaseRow}> Add </button>


      </div>
      <div className="container">
        <form onSubmit={handleEditFormSubmit} >
          <Table striped bordered hover responsive variant="light">
            <thead>
              <tr>
                <th>
                  {" "}
                  <h6> Injection Speed </h6>{" "}
                </th>
                <th>
                  {" "}
                  <h6> Fill Time </h6>{" "}
                </th>
                <th>
                  {" "}
                  <h6> Peak Inj Press </h6>{" "}
                </th>
                <th>
                  {" "}
                  <h6> Viscocity </h6>{" "}
                </th>
                <th>
                  {" "}
                  <h6> Shear Rate </h6>{" "}
                </th>
                <th>
                  {" "}
                  <h6> AbsoluteDropViscocity </h6>{" "}
                </th>
                <th>
                  {" "}
                  <h6> %DropViscocity </h6>{" "}
                </th>
                <th>
                  {" "}
                  <h6> Action </h6>{" "}
                </th>
              </tr>
            </thead>
            <tbody className="grid_style">
              {NewRow2.map((element, rowId) => {
                return (
                  <tr key={rowId}>

                    <td> <input type='text' className="form-control" defaultValue={element.Injection_Speed} name="Injection_Speed" onChange={handleEditFormChange} onClick={() => demo(rowId)} /> </td>

                    <td> <input type='text' className="form-control" defaultValue={element.Fill_Time} name="Fill_Time" onChange={handleEditFormChange} onClick={() => demo(rowId)}/></td>

                    <td><input type='text' className="form-control" defaultValue={element.Peak_Inj_Press} name="Peak_Inj_Press" onChange={handleEditFormChange} onClick={() => demo(rowId)}/> </td>

                    <td> <input type='text' className="form-control" name="Viscosity" value={isNaN(Math.round(element.Viscosity)) ? '-' : Math.round(element.Viscosity) } onChange={handleEditFormChange} onClick={() => demo(rowId)} readOnly/> </td>

                    <td>  <input type='text' className="form-control" name="Shear_Rate" value={isNaN(Number(element.Shear_Rate).toFixed(3)) ? '-' : Number(element.Shear_Rate).toFixed(3)} readOnly /> </td>

                    <td> <input type='text' className="form-control" readOnly /></td>

                    <td> <input type='text' className="form-control" readOnly /></td>

                    <td> <i className="fa fa-trash viscocity_icons" onClick={() => deleteRow2(element)}></i> </td>
                  </tr>
                )
              })}
              {NewRow.map((rowId) => {
              return (
                <tr key={rowId}>
                  <td>
                    <input type="text" className="form-control" />
                  </td>
                  <td>
                    <input type="text" className="form-control" />
                  </td>
                  <td>
                    <input type="text" className="form-control" />
                  </td>
                  <td>
                    <input type="text" className="form-control" readOnly />
                  </td>
                  <td>
                    <input type="text" className="form-control" readOnly />
                  </td>
                  <td>
                    <input type="text" className="form-control" readOnly />
                  </td>
                  <td>
                    <input type="text" className="form-control" readOnly />
                  </td>
                  <td>
                    <i
                      className="fa fa-trash viscocity_icons"
                      onClick={() => deleteRow(rowId)}
                    >
                    </i>
                  </td>
                </tr>
              );
            })}
            </tbody>
          </Table>
          <button type="submit"> Calculate </button>
        </form>
      </div>
    </>
  );
};

export default App;

https://codesandbox.io/s/practical-torvalds-jj3h2?file=/src/App.js

您必须使用数组并将数据保存到该数组中:

import { useState } from "react";
import Table from "react-bootstrap/Table";
const rowData = {
    Injection_Speed: "",
    Fill_Time: "",
    Peak_Inj_Press: "",
    Viscosity: "",
    Shear_Rate: "",
    Absolute_Drop_Viscosity: ""
};
const App = () => {
  const [row, setRow] = useState();
  const [allRowsAdded, updateAllRows] = useState(0);
  const [viscosity, setViscosity] = useState([]);

  const [IntensificationRatio, setIntensificationRatio] = useState(1)
  const [editFormData, setEditFormData] = useState([rowData])
  const [isRowId, setIsRowId] = useState(null)

  const handleEditFormChange = (event, fieldName, index) => {
    event.preventDefault();

    const fieldValue = event.target.value;

    setEditFormData(prevState => {
        const newState = [...prevState];
        newState[index][fieldName] = fieldValue;
        return newState;
    })
  }

  const handleEditFormSubmit = (event) => {
      event.preventDefault();

      setEditFormData(prevState => {
        const newState = [...prevState];
        newState.map(item => {
            let viscosity = item['Fill_Time'] * item['Peak_Inj_Press'] * IntensificationRatio;
            viscosity = isNaN(Math.round(viscosity)) ? '-' : Math.round(viscosity)
            let shearRate = 1 / item['Fill_Time'];
            shearRate = isNaN(Number(shearRate).toFixed(3)) ? '-' : Number(shearRate).toFixed(3)
            item.Viscosity = viscosity;
            item.Shear_Rate = shearRate;
        })
        return newState;
      });
  }

  const addRow = (e) => {
    e.preventDefault();
    setRow(e.target.value);
  };

  const increaseRow = () => {
    setEditFormData(prevState => {
        const newState = [...prevState];
        for (let i = 0; i < parseInt(row); i++) {
            newState.push(rowData);
        }
        return newState;
    })
  };

  const deleteRow = (key) => {
    setEditFormData(prevState => {
        const newState = prevState.splice(key, 1);
        return newState;
    })
  };

  const demo = (id) => {
    setIsRowId(id)
  }

  return (
    <>
      <div>
        <form>
          <input type="text" onChange={addRow} placeholder="Enter Number Of Row's" /><br />
          <input type="text" onChange={(e) => setIntensificationRatio(e.target.value)} placeholder="Enter Intensification Ratio" />
        </form>
        <button onClick={increaseRow}> Add </button>
      </div>

      <div className="container">
        <form onSubmit={handleEditFormSubmit} >
          <Table striped bordered hover responsive variant="light">
            <thead>
              <tr>
                <th>
                  {" "}
                  <h6> Injection Speed </h6>{" "}
                </th>
                <th>
                  {" "}
                  <h6> Fill Time </h6>{" "}
                </th>
                <th>
                  {" "}
                  <h6> Peak Inj Press </h6>{" "}
                </th>
                <th>
                  {" "}
                  <h6> Viscocity </h6>{" "}
                </th>
                <th>
                  {" "}
                  <h6> Shear Rate </h6>{" "}
                </th>
                <th>
                  {" "}
                  <h6> AbsoluteDropViscocity </h6>{" "}
                </th>
                <th>
                  {" "}
                  <h6> %DropViscocity </h6>{" "}
                </th>
                <th>
                  {" "}
                  <h6> Action </h6>{" "}
                </th>
              </tr>
            </thead>
            <tbody className="grid_style">
              {editFormData.map((element, rowId) => {
                return (
                  <tr key={rowId}>

                    <td> <input type='text' className="form-control" defaultValue={element.Injection_Speed} onChange={e => handleEditFormChange(e, 'Injection_Speed',rowId)} onClick={() => demo(rowId)} /> </td>

                    <td> <input type='text' className="form-control" defaultValue={element.Fill_Time} onChange={e => handleEditFormChange(e,'Fill_Time',rowId)} onClick={() => demo(rowId)}/></td>

                    <td><input type='text' className="form-control" defaultValue={element.Peak_Inj_Press} onChange={e => handleEditFormChange(e, 'Peak_Inj_Press',rowId)} onClick={() => demo(rowId)}/> </td>

                    <td> <input type='text' className="form-control" value={element.Viscosity } onChange={e => handleEditFormChange(e,rowId)} onClick={() => demo(rowId)} readOnly/> </td>

                    <td>  <input type='text' className="form-control" value={element.Shear_Rate} readOnly /> </td>

                    <td> <input type='text' className="form-control" readOnly /></td>

                    <td> <input type='text' className="form-control" readOnly /></td>

                    <td> <i className="fa fa-trash viscocity_icons" onClick={() => deleteRow(element, rowId)}></i> </td>
                  </tr>
                )
              })}
            </tbody>
          </Table>
          <button type="submit"> Calculate </button>
        </form>
      </div>
    </>
  );
};

export default App;

https://codesandbox.io/s/cold-field-8ktxz?file=/src/App.js