如何使用反应创建可重用的输入字段?

时间:2020-12-22 13:50:46

标签: reactjs forms react-functional-component

我有 InputField 组件,它接受各种道具,如类型、占位符、值等。我正在尝试使用 InputField 组件创建一个表单。我可以轻松地从表单传递道具,但我无法将输入值保存到我的状态。 这是我的代码。

<块引用>

InputField.js

@fallbackXXX
<块引用>

AddProductForm.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;

1 个答案:

答案 0 :(得分:3)

尝试从 InputField event 而不是 value 传递。 然后在 handler 中,您可以使用 input name 并了解应该更新哪个字段。

当然,首先为 name 添加 input 字段,如下所示:

InputField.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;

AddProductForm.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;