问题描述
我想知道是否有一个优雅的和/或推荐的解决方案来解决这个问题。
如果我有一个用于数字的输入,并且想输入一个负数,则首先必须输入-
符号。
当我输入时, parseInt
将返回NaN
,这是可以理解的。
但是,如果输入的值绑定到parseInt
的结果,那么我将永远无法完成输入数字,因为一旦尝试将-
解析为int它将失败。
const { useState } = React; const App = () => { const [count, setCount] = useState(0); const [inputValue, setInputValue] = useState('') const update = ({ target }) => { const { value } = target; const attemptedParse = parseInt(value); if (!attemptedParse) { setInputValue(value); setCount(0); } else { setInputValue(attemptedParse); setCount(attemptedParse); } } return ( <div> <h1>{count}</h1> <input value={inputValue} onChange={update} /> </div> ) }; ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.1/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.1/umd/react-dom.production.min.js"></script> <div id="root"></div>
上面的解决方案使用两种单独的状态 ,一种用于输入,另一种用于实际值。 但这似乎有点混乱,我想知道是否有人有涉及更少代码的解决方案。
1楼
您可以使用正则表达式
const { useState } = React; const App = () => { const [count, setCount] = useState(0); const [inputValue, setInputValue] = useState('') const update = ({ target }) => { var { value } = target; // Replace all non-numeric characters to '' value = value.replace(/[^0-9-]+/g, ''); // The real pattern you are looking for var pattern = /([-])?([0-9]+)/g; var matches = value.match(pattern); if(matches){ value = matches[0]; } setInputValue(value); setCount(value); } return ( <div> <h1>{count}</h1> <input value={inputValue} onChange={update} /> </div> ) }; ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.1/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.1/umd/react-dom.production.min.js"></script> <div id="root"></div>
2楼
应该有两种状态,一种用于输入值,另一种用于解析的整数。
输入值不一定必须重置为已解析的整数,这可能会使输入更加麻烦,例如在负数的情况下:
const update = ({ target }) => {
const { value } = target;
const attemptedParse = parseInt(value);
if (!Object.is(NaN, attemptedParse)) {
setCount(attemptedParse);
}
}