[英]Why can't I save a number with decimal values in my input box? It only allows integers to be updated?
I have an text input box on my form, and when the form initially displays it displays the price with a decimal point like 910.01
.我的表单上有一个文本输入框,当表单最初显示时,它会显示带有小数点的价格,如
910.01
。
const initialState: OrderWindowState = {
price1: 910.01,
price2: 911.33,
}
const [state, setState] = useState<OrderWindowState>(initialState);
<input type="text" name="price1" value={state.price1} onChange={price1OnChange} />
const price1OnChange = (event: React.ChangeEvent<HTMLInputElement>) => {
event.preventDefault();
console.log("price1OnChange called:" + event.target.value);
setState({
...state,
price1: +event.target.value
})
};
When I begin to update the number, if I enter a decimal point .
当我开始更新数字时,如果我输入小数点
.
I can see it in my console.log
message, but the number stored in my state and visibly in my text input it only displays integer values (with no decimal values).我可以在我的
console.log
消息中看到它,但是存储在我的 state 中并且在我的文本输入中可见的数字只显示 integer 值(没有十进制值)。
Why is it doing this?为什么要这样做?
When you do +event.target.value
, the string value is converted into a number - and numbers don't have trailing .
当您执行
+event.target.value
时,字符串值将转换为数字 - 并且数字没有尾随.
s. s。 So, when the component re-renders, the previously typed
.
因此,当组件重新渲染时,之前键入的
.
won't be reflected in state, so it won't be seen in the controlled component's value either.不会反映在 state 中,因此也不会在受控组件的值中看到。
One approach would be to keep the string input in state, and to only convert it to a number later when needed.一种方法是将字符串输入保留在 state 中,并仅在以后需要时将其转换为数字。 For example:
例如:
const App = () => { const [price1, setPrice1] = React.useState(910.01); const price1OnChange = (event) => { setPrice1(event.target.value); }; const price1Number = Number(price1); return ( <div> <input type="text" name="price1" value={price1} onChange={price1OnChange} /> <div> Number value: {Number.isNaN(price1Number)? 'Not a number - correct your input': price1Number} </div> </div> ); }; ReactDOM.createRoot(document.querySelector('.react')).render(<App />);
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script> <div class='react'></div>
The above is in JS just so that the snippet can be run easily, but the same approach works for TypeScript - change your OrderWindowState
to accept strings instead of numbers, and change price1: +event.target.value
to price1: event.target.value
.以上是在 JS 中,以便可以轻松运行代码段,但同样的方法适用于 TypeScript - 将
OrderWindowState
更改为接受字符串而不是数字,并将 price1 price1: +event.target.value
更改为 price1 price1: event.target.value
。
Because the values for price1 and price2 are separate, you might consider using separate states for them (like I did above and as React recommends).因为 price1 和 price2 的值是分开的,所以您可以考虑为它们使用不同的状态(就像我在上面所做的那样,并且按照 React 的建议)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.