繁体   English   中英

如何获得输入的总和

[英]How to get summation of inputs

在此处输入图像描述

import React, { useEffect, useState } from "react";

export default function App() {
  const items = [
    { store: { name: "store a", id: 0 }, months: ["june", "july"] },
    { store: { name: "store b", id: 2 }, months: ["agust", "septm"] },
    { store: { name: "store c", id: 3 }, months: ["novem", "decemb"] },
  ];

  return (
    <table>
      {items.map((item, index) => {
        const storeName = item.store.name;
        return (
          <tr key={item.store.id}>
            <th>{storeName}</th>
            {item.months.map((month, i) => (
              <td>
                <input type="text" />
              </td>
            ))}
            <td style={{ width: "100px" }}>total:</td>
          </tr>
        );
      })}
    </table>
  );
}

我想实现这个 ui 并在每一行中显示输入总和 我应该如何实现它的功能?

import React, { useEffect, useState } from "react";

export default function App() {
  const [inputData, setInputData] = useState(null);
  const items = [
    { store: { name: "store a", id: 0 }, months: ["june", "july"] },
    { store: { name: "store b", id: 2 }, months: ["agust", "septm"] },
    { store: { name: "store c", id: 3 }, months: ["novem", "decemb"] },
  ];
  useEffect(() => {
    let data = {};
    items.forEach((item) => {
      data = { ...data, [item.store.name]: [] };
    });
    setInputData(data);
  }, []);
  function getSum(total, num) {
    return total + Number(num);
  }
  
  return (
    <table>
      {inputData &&
        items.map((item, index) => {
          const storeName = item.store.name;
          return (
            <tr key={item.store.id}>
              <th>{storeName}</th>
              {item.months.map((month, i) => (
                <td>
                  <input
                    type="text"
                    value={inputData && inputData[items[index].store.name][i]}
                    onChange={(e) => {
                      let montData = [...inputData[storeName]];
                      montData[i] = e.target.value;
                      setInputData({
                        ...inputData,
                        [storeName]: montData,
                      });
                    }}
                  />
                </td>
              ))}
              <td style={{ width: "100px" }}>
                total: {inputData[storeName].reduce(getSum, 0)}
              </td>
            </tr>
          );
        })}
    </table>
  );
}

https://codesandbox.io/s/blissful-neco-xc8ury

暂无
暂无

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

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