当我使用 React-hooks 从 onchange 输入获取值时保持变量类型 [英] keep a variable type when I get value from input onchange with React-hooks

查看:33
本文介绍了当我使用 React-hooks 从 onchange 输入获取值时保持变量类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

const { useState } = React;const App = () =>{const [num, setNum] = useState(0);返回 (<input type="number" value={num} onChange={(e)=>setNum(parseInt(e.target.value))}/>)}ReactDOM.render(, document.getElementById('root'));

<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script><div id="root"/>

我想保持 num 的类型为 Number,而不是 String.

但是,onChange=(e=>setNum(e.target.value)) 使得 num 的类型为 String

我试着像这样改变onChange={e=>setNum(parseInt(e.target.value))}.

但是,当我输入white-space时,出现错误.

<块引用>

警告:收到 value 属性的 NaN.如果这是预期的,请将值转换为字符串.

保持 num 类型的最佳方法是什么?

解决方案

问题源于 parseInt 可能会中断.

如果您无法成功解析字符串"输入值,您将收到错误消息.您可以向当前值添加回退或重置为 0,或者在 parseInt 失败时避免调用 setNum.

import React, { useState } from 'react';const 应用程序:React.FC = () =>{const [num, setNum] = useState(0);返回 (<输入类型=数字"onChange={e =>setNum(parseInt(e.target.value) || num)}/>);};导出默认应用程序;

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?

解决方案

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;

这篇关于当我使用 React-hooks 从 onchange 输入获取值时保持变量类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆