问题
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