简体   繁体   中英

How to move uncontrolled component to controlled component

I am creating a form by custom form react bootstrap, but I have an issue that,

A component is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component

That is my input form is uncontrolled. How can I change it to controlled input form to allow user to enter what they want?

const ProductForm = ({ product, onSave }) => {

const [value, setValues] = useState(product);



     useEffect(() => {
    setValues({
      product: {
        image: "",
        name: "",
        price: 0,
        description: "",
        categoty: ""
      }
    });
  }, []);

  const handleInputChange = event => {
    // Create new product to update
    const newPropdudct = {
      ...value,
      [event.target.name]: event.target.value
    }
    // Update new product for value
    setValues(newPropdudct);
  }  

///////////////////////////////////////////////////////////

<Form.Group>

     <Form.Group>
       <Form.File
          id="image"
          label="Image choose"
          value={value.image}
          onChange={handleFileChange} />
     </Form.Group>
</Form.Group>

<Form.Group controlId="name">
    <Form.Label>Name</Form.Label>
       <Form.Control
          type="text"
          placeholder="Enter product name"
          value={value.name}
          name="name"
          onChange={handleInputChange}
       />
   </Form.Group> 

The reason is, in state you defined:

const [value, setValues] = useState(product);

also in your useEffect there is a product property and inside that a name property:

setValues({
     product: {
        image: "",
        name: "",
        price: 0,
        description: "",
        categoty: ""
     }
});

and in your form control

value={value.name}

during the first rendering the value of the form will be undefined, and the input field will get its value as:

value={undefined}

Because of that, the input field will become uncontrolled.

it should be :

value={value.product.name}

and your handleInputChange function should be:

handleInputChange = event => {
    // Create new product to update
    const newPropdudct = {
      product: {
          ...value.product,
          [event.target.name]: event.target.value
      }
    }
    // Update new product for value
    setValues(newPropdudct);
  }  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM