use*_*304 8 forms reactjs react-functional-component
我有InputField 组件,它接受各种道具,如类型、占位符、值等。我正在尝试使用InputField 组件创建一个表单。我可以轻松地从表单传递道具,但无法将输入值保存到我的状态中。这是我的代码。
输入字段.js
import React, { useState } from "react";
const InputField = ({ value, label, placeholder, type, onChange }) => {
const handleChange = (e) => {
const { value } = e.target;
onChange(value);
};
return (
<div className="form-group">
{label && <label htmlFor="input-field">{label}</label>}
<input
type={type}
value={value}
className="form-control"
placeholder={placeholder}
onChange={handleChange}
/>
</div>
);
};
export default InputField;
Run Code Online (Sandbox Code Playgroud)
添加产品表单.js
import React, { useState } from "react";
import { Form, Button } from "reactstrap";
import InputField from "../UI/InputField";
const AddProductForm = () => {
const [inputValue, setInputValue] = useState({ name: "", price: "" });
const { name, price } = inputValue;
const handleChange = (inputValue) => {
setInputValue({ name: inputValue, price: inputValue });
console.log(inputValue);
};
return (
<Form>
<InputField
type="text"
value={name}
placeholder="Product Name"
label="Name"
onChange={handleChange}
/>
<InputField
type="number"
value={price}
placeholder="Add Price"
label="Price"
onChange={handleChange}
/>
<Button color="primary">Add</Button>{" "}
<Button color="secondary">Cancel</Button>
</Form>
);
};
export default AddProductForm;
Run Code Online (Sandbox Code Playgroud)
Xom*_*9ik 27
InputField event尝试从而不是传递value。然后,handler您可以了解input name并了解应该更新哪个字段。
当然,首先添加name字段 for ,input如下所示:
输入字段.js
import React from "react";
const InputField = ({ value, label, name, placeholder, type, onChange }) => (
<div className="form-group">
{label && <label htmlFor="input-field">{label}</label>}
<input
type={type}
value={value}
name={name}
className="form-control"
placeholder={placeholder}
onChange={onChange}
/>
</div>
);
export default InputField;
Run Code Online (Sandbox Code Playgroud)
添加产品表单.js
import React, { useState } from "react";
import InputField from "../UI/InputField";
const AddProductForm = () => {
const [inputValue, setInputValue] = useState({ name: "", price: "" });
const { name, price } = inputValue;
const handleChange = (e) => {
const { name, value } = e.target;
setInputValue((prev) => ({
...prev,
[name]: value,
}));
console.log(inputValue);
};
return (
<Form>
<InputField
type="text"
value={name}
placeholder="Product Name"
label="Name"
name="name"
onChange={handleChange}
/>
<InputField
type="number"
value={price}
placeholder="Add Price"
label="Price"
name="price"
onChange={handleChange}
/>
<Button color="primary">Add</Button>{" "}
<Button color="secondary">Cancel</Button>
</Form>
);
};
export default AddProductForm;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27123 次 |
| 最近记录: |