reactjs React Hook Number + Number保存到新数据中是否可能?

nzk0hqpo  于 2023-04-05  发布在  React
关注(0)|答案(1)|浏览(95)

例如,我有2个大小的小和中等。我如何才能保存两个数据加在一起成为一个新的totalCount数据或任何最佳做法的代码下面的代码,请

const [sizeSmall, setSizeSmall] = useState(0)
const [sizeMed, setSizeMed] = useState(0)
const [totalCount, setTotalCount] = useState(0)   // This will be sizeSmall + sizeMed add together

**// How can I make the total of both sizes into one total

<input 
type=number
value = {sizeSmall}
onChange = (e => setSizeSmall(e.target.value)
 required
/>

<input
type=number
value = {sizeMed}
onChange = (e => sizeMed(e.target.value)
 required
/>
u3r8eeie

u3r8eeie1#

现在起作用了

const [sizeSmall, setSizeSmall] = useState(0);
const [sizeMed, setSizeMed] = useState(0);
const [totalCount, setTotalCount] = useState(0);

useEffect(() => {
  setTotalCount(parseInt(sizeSmall) + parseInt(sizeMed));
}, [sizeSmall, sizeMed]);

return (
  <>
    <input
      type="number"
      value={sizeSmall}
      onChange={(e) => {
        setSizeSmall(e.target.value);
      }}
      required
    />

    <input
      type="number"
      value={sizeMed}
      onChange={(e) => {
        setSizeMed(e.target.value);
      }}
      required
    />

    <p>Total Count: {totalCount}</p>
  </>
);

相关问题