keep a variable type when I get value from input onchange with React-hooks

限于喜欢 提交于 2021-02-11 08:25:25

问题


const { useState } = React;

const App = () => {
  const [num, setNum] = useState(0);
  
  return (
    <input type="number" value={num} onChange={(e)=>setNum(parseInt(e.target.value))} />
  )
}

ReactDOM.render(<App />, document.getElementById('root'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root" />

I want to keep num's type as Number, not String.

but, onChange=(e=>setNum(e.target.value)) makes num's type String

I tried to change like this onChange={e=>setNum(parseInt(e.target.value))}.

but, when I inputted white-space, It occurs error.

Warning: Received NaN for the value attribute. If this is expected, cast the value to a string.

What is the best way to keep num's type?


回答1:


The issue stems from the fact that parseInt can break.

In case you cannot successfully parseInt your "string" input value, you will get an error. You can add a fallback to current value or reset to 0, or avoid calling setNum in case your parseInt fails.

import React, { useState } from 'react';

const App: React.FC = () => {
  const [num, setNum] = useState(0);

  return (
    <input
      type="number"
      onChange={e => setNum(parseInt(e.target.value) || num)}
    />
  );
};

export default App;


来源:https://stackoverflow.com/questions/56381007/keep-a-variable-type-when-i-get-value-from-input-onchange-with-react-hooks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!