更新反应表单中的输入类型编号

Mam*_*hid 6 javascript reactjs react-hooks

我正在尝试更新输入值。它工作正常,正在更新其值。但是,有一个问题,当它更新其值时,它会从数字转换为字符串。我已经尝试过NumberparseInt,但它不起作用。它总是转换为字符串。

import React from 'react';
import useForm from '../lib/useForm';

const CreateProduct = () => {
  const { input, handleChange } = useForm({
    name: 'mama',
    price: 0,
  });
  return (
    <form>
      <label htmlFor="price">
        Price
        <input
          type="number"
          id="price"
          name="price"
          placeholder="Price"
          value={parseInt(input.price)}
          onChange={handleChange}
        />
      </label>
    </form>
  );
};

export default CreateProduct;
Run Code Online (Sandbox Code Playgroud)

在自定义函数中:

import * as React from 'react';

export default function useForm(initialValue = {}) {
  const [input, setInput] = React.useState(initialValue);

  function handleChange(event) {
    const { name, value } = event.target;
    setInput({
      ...input,
      [name]: value,
    });
  }
  return {
    input,
    handleChange,
  };
}

Run Code Online (Sandbox Code Playgroud)

这是初始状态: 在此输入图像描述

这是更新后的状态,其中包含数字陷阱 在此输入图像描述

Dre*_*ese 5

问题

输入仅处理字符串。如果您希望该值是除此之外的任何值,则应在传递给处理程序时或在处理程序本身中对其进行转换。

解决方案

在处理程序中处理时将值转换回数字

function handleChange(event) {
  const { name, type, value } = event.target;

  setInput(input => {
    const nextInput = {...input}

    switch(type) {
      case 'number':
        nextInput[name] = Number(value);
        break;

      // handle other input type cases

      default:
        nextInput[name] = value;
    }
    return nextInput;
  });
}
Run Code Online (Sandbox Code Playgroud)

编辑react-form中的updated-input-type-number-number-in-react-form