Mam*_*hid 6 javascript reactjs react-hooks
我正在尝试更新输入值。它工作正常,正在更新其值。但是,有一个问题,当它更新其值时,它会从数字转换为字符串。我已经尝试过Number、parseInt,但它不起作用。它总是转换为字符串。
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)
输入仅处理字符串。如果您希望该值是除此之外的任何值,则应在传递给处理程序时或在处理程序本身中对其进行转换。
在处理程序中处理时将值转换回数字
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)
| 归档时间: |
|
| 查看次数: |
3150 次 |
| 最近记录: |