反应:用最后两个输入数字设置值

遇到情况,我不知道如何解决。在此输入中写入数字时,无论我输入多少个数字,我都只想看到最后插入的两个数字。例子:


Input = 5  Value = 5

Input = 59 Value = 59

Input = 597 Value = 97

Input = 5970 Value = 70

Input = 59701 Value = 01

等等。


const [number, setNumber] = useState(0);

function handleChange(e) {

  setNumber(e.target.value);

}

return (

  <div>

    <input type="text" maxLength="2" value={number} onChange={handleChange} />

  </div>

)


临摹微笑
浏览 91回答 1
1回答

喵喔喔

转移到字符串然后使用slice()剪切最后 2 个数字const&nbsp;result&nbsp;=&nbsp;Number(e.target.value.toString().slice(-2));const App = () => {&nbsp; const [number, setNumber] = React.useState(0);&nbsp; function handleChange(e) {&nbsp; &nbsp; const result = Number(e.target.value.toString().slice(-2));&nbsp; &nbsp; setNumber(result);&nbsp; &nbsp; console.log(result);&nbsp; }&nbsp; return (&nbsp; &nbsp; <div className="App">&nbsp; &nbsp; &nbsp; <input type="text" value={number} onChange={handleChange} />&nbsp; &nbsp; </div>&nbsp; );}ReactDOM.render(<App />, document.getElementById("root"));<div id="root"></div><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>或者更复杂的方式如下使用split(),pop(),join()const x = e.target.value.toString().split('');const y = [x.pop(), x.pop()].reverse();const result = Number(y.join(''));const App = () => {&nbsp; const [number, setNumber] = React.useState(0);&nbsp; function handleChange(e) {&nbsp; &nbsp; const x = e.target.value.toString().split('');&nbsp; &nbsp; const y = [x.pop(), x.pop()].reverse();&nbsp; &nbsp; const result = Number(y.join(''));&nbsp; &nbsp; setNumber(result);&nbsp; &nbsp; console.log(result);&nbsp; }&nbsp; return (&nbsp; &nbsp; <div className="App">&nbsp; &nbsp; &nbsp; <input type="text" value={number} onChange={handleChange} />&nbsp; &nbsp; </div>&nbsp; );}ReactDOM.render(<App />, document.getElementById("root"));<div id="root"></div><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>一旦你完全控制了绑定到onChangeand的处理函数value,就不需要maxLength&nbsp;defaultValue相关的 props。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript