reactjs - 反应输入中的格式数字
问题描述
我需要在反应中格式化输入,添加后缀“g”。对于结果输入,它可以,但是对于 input1 和 input2,当我将类型更改为文本时,它无法正常工作。链接codesandbox:https ://codesandbox.io/s/eager-meitner-ez7wo?file=/src/index.js
非常感谢你们。
import React, {useState} from 'react'
import ReactDOM from 'react-dom'
function App() {
const [input1, setInput1] = useState(2);
const [input2, setInput2] = useState(3);
const updateInput1 = (event) => {
const inputValue1 = event.target.value
setInput1(parseInt(inputValue1))
}
const updateInput2 = (event) => {
const inputValue2 = event.target.value
setInput2(parseInt(inputValue2))
}
const addInputs =()=> input1 + input2;
return <>
<label>
Input1
</label>
<input
type="number"
onChange={updateInput1}
value={input1}
>
</input>
<label>
Input2
</label>
<input
type="number"
onChange={updateInput2}
value={input2}
>
</input>
<label>
Result
</label>
<input
type="text"
value={addInputs() + "g"}
>
</input>
</>
}
ReactDOM.render(<App />, document.getElementById('root'))
解决方案
event.target.value
正在返回一个字符串。修复代码所需要做的就是将两个输入都转换回整数,然后再设置它们,如下所示:
const updateInput1 = (event) => {
const inputValue1 = event.target.value
setInput1(parseInt(inputValue1))
}
const updateInput2 = (event) => {
const inputValue2 = event.target.value
setInput2(parseInt(inputValue2))
}
推荐阅读
- oop - 为什么我的表返回 NIL 并且没有填充?
- javascript - 如何将 chessboard.js 节点模块导入 Angular 项目?
- python - 映射/连接到发布 Django 网站时的错误请求问题
- sql - IBM Db2 on Cloud 中使用的 SQL 方言是什么
- visual-studio-code - 在 Visual Studio Code 中的模板字符串之间添加用户创建的片段
- forth - 在 Forth 中执行一个字符或字符串,就好像它是一个单词一样
- python - python中的回溯是什么?
- python - 如何在 Python 中实现和执行多个类的线程?
- django-views - 类型错误 Django 3.0.4:运行服务器时出现类型错误
- javascript - “枚举”具有自定义数字序列的字符串?