How to implement a dynamic form with controlled components in ReactJS?

后端 未结 4 1565
野性不改
野性不改 2020-11-29 22:18

As I am looking at the examples in the reference for controlled form components in react.js official website, I am wondering how is one supposed to implement a

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-29 23:02

    How adding/removing input elements dynamically with functional components?

    The same component from the selected answer reviewed and rewrited as a functional component.

    import React from 'react';
    import { useState } from 'react';
    
    function DynamicInput() {
    
        const [values, setValues] = useState({ val: []});
    
          function createInputs() {
            return values.val.map((el, i) =>
              
    ); } function handleChange(event) { let vals = [...values.val]; vals[this] = event.target.value; setValues({ val: vals }); } const addClick = () => { setValues({ val: [...values.val, '']}) } const removeClick = () => { let vals = [...values.val]; vals.splice(this,1); setValues({ val: vals }); } const handleSubmit = event => { alert('A name was submitted: ' + values.val.join(', ')); event.preventDefault(); } return (
    {createInputs()}
    ); } export default DynamicInput;

提交回复
热议问题