簡體   English   中英

“數字”類型的輸入元素的初始值為空 - React 和 Tsx

[英]Initial value from an input element of type 'number' is Empty - React and Tsx

我正在使用 Typescript 開發 React POS 應用程序。我想計算當我輸入從買家那里收到的金額時的變化。 當我將值輸入輸入元素時,傳遞給計算更改的邏輯的第一個值是一個空值,然后添加其他值。 它會導致計算不准確。

const CartBill: React.FC<{}> = () => {
  const [change, setChange] = useState<number>(0)
//logic to calculate change
const calculateChange: changeCalculatorType = (amountReceived) => {

    if (amountReceived <= +grandTotal.toFixed(2)) {
      setChange(0);
    } else {
      const change = amountReceived - +grandTotal.toFixed(2);
      setChange(+change.toFixed(2));
    }
    return change;
  };

return(
   <div> <Received onSetChange={calculateChange} /> </div>
   <div>{change}</div>
)
} 

這是包含輸入元素的組件。 它將amount state 提升到CartBill組件

import {useState} from 'react'
import { changeCalculatorType } from '../../types/ReceivedComponentTypes';




const Received: React.FC<{ onSetChange: changeCalculatorType }> = (props) => {
  const [amount, setAmount] = useState(0);

  const getInputHandler = (event: React.FormEvent<HTMLInputElement>) => {
    const retrieved = +(event.target as HTMLInputElement).value.trim();
    
    setAmount(retrieved);
    props.onSetChange(amount);
   
  };
  return (
    <>
      <input type="number" name="" id="" onChange={getInputHandler} />
    </>
  );
};

export default Received

我試過trim()值,但這似乎不起作用。 非常感謝任何幫助

您需要在input上設置 value 屬性。

return (
  <input type="number" name="" id="" value={amount} onChange={getInputHandler} />
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM