[英]How can I make a text box in React which allows only numbers or an empty value, which triggers the number keypad on mobile?
[英]Why can't I save a number with decimal values in my input box? It only allows integers to be updated?
我的表单上有一个文本输入框,当表单最初显示时,它会显示带有小数点的价格,如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
})
};
当我开始更新数字时,如果我输入小数点.
我可以在我的console.log
消息中看到它,但是存储在我的 state 中并且在我的文本输入中可见的数字只显示 integer 值(没有十进制值)。
为什么要这样做?
当您执行+event.target.value
时,字符串值将转换为数字 - 并且数字没有尾随.
s。 因此,当组件重新渲染时,之前键入的.
不会反映在 state 中,因此也不会在受控组件的值中看到。
一种方法是将字符串输入保留在 state 中,并仅在以后需要时将其转换为数字。 例如:
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>
以上是在 JS 中,以便可以轻松运行代码段,但同样的方法适用于 TypeScript - 将OrderWindowState
更改为接受字符串而不是数字,并将 price1 price1: +event.target.value
更改为 price1 price1: event.target.value
。
因为 price1 和 price2 的值是分开的,所以您可以考虑为它们使用不同的状态(就像我在上面所做的那样,并且按照 React 的建议)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.