首页 > 解决方案 > 反应输入中的格式数字

问题描述

我需要在反应中格式化输入,添加后缀“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'))


标签: reactjsinputformat

解决方案


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))
 }

推荐阅读