【问题标题】:Get value from appended child component in React从 React 中附加的子组件获取值
【发布时间】:2021-01-22 21:08:16
【问题描述】:

我有一个主要的反应组件,它在按钮单击时附加子组件说<Child />

我的Child 组件的格式为

<form>
    <input .... />
    <button type="submit">Submit</button>
<form>

现在我需要从每个附加的 Child 组件中获取这些 input 元素的值,但我无法找到这样做的方法。

我不知道会添加多少个Child 组件,因为用户可以多次单击该按钮以附加另一个&lt;Child /&gt;,因此我无法从子级导出固定数量的变量组件到父组件中的变量。

任何建议都将受到高度赞赏。

编辑:

附加孩子的代码:

  • submit 函数:
const [val, setVal] = useState([]);

const submit = () => {
    setVal([...val, <Child />]);
}
  • 附加按钮:
<Button onClick={submit}>Add Child</Button>
  • 渲染:
{val}

由于val 是一个数组,它会打印其中的所有组件

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    我冒昧了,因为我不知道所有表单的预期输出是什么。

    我基本上所做的是创建一个类似映射的结构,在其中我将映射每个子表单及其值(取决于您的需要可以修改),然后我按顺序将submit 函数传递给子组件将值存储在父级上。

    通过这种方式,在子提交时,我将能够获取从子传递的值及其索引。

    父组件

    const Parent = () => {
      const [val, setVal] = useState([]);
      // Map like structure to store the values (is just an example, you can use whatever you want)
      const [mapOfValues, setMapOfValues] = useState({});
    
      // Pass submit function as prop
      const submit = () => {
        setVal([...val, <Child submit={onChildSubmit} />]);
      };
    
      // Submit function that stores the value for the child
      const onChildSubmit = (childIndex, value) => {
        setMapOfValues({
          ...mapOfValues,
          [childIndex]: value
        });
      };
    
      return (
        <div className="App">
          {val.map((value, index) =>
            // Key to prevent React warning and childIndex to map the value to the child form
            React.cloneElement(value, { key: index, childIndex: index })
          )}
          <button onClick={submit}>Add</button>
        </div>
      );
    }
    
    

    子组件

    const Child = (props) => {
      const [value, setValue] = useState("");
    
      const submitForm = (e) => {
        e.preventDefault();
        props.submit(props.childIndex, value);
      };
    
      return (
        <form onSubmit={submitForm}>
          <input onChange={(e) => setValue(e.target.value)} value={value} />
          <button>Submit</button>
        </form>
      );
    };
    

    完成后,如果您想从父组件提交,您可以使用reducemap 或任何您需要的格式来设置您想要的值。

    沙盒的链接是this

    如果您有任何其他问题,请告诉我。

    【讨论】:

    • 该死的,这就像一个魅力另外,如果我没记错的话,Child 是通过 prop 直接访问父函数onChildSubmit 对吗?我不知道我们也可以将函数作为道具传递,这真的很棒
    • @luckongas 我也尝试像onChildSubmit 一样实现onChildDelete。我能够使用带有临时变量的delete 使其适用于mapOfValues;但我无法为val 做同样的事情。我尝试使用const tempField = educationFields.splice(childIndex, 1); setEducationFields(tempField),但如果我尝试删除第一个元素,则会清空我的整个数组。而不是仅仅删除第一个元素。如果您能为此提出一种方法,那就太好了
    猜你喜欢
    • 2021-11-10
    • 2016-06-18
    • 1970-01-01
    • 2014-08-19
    • 2020-03-25
    • 1970-01-01
    • 1970-01-01
    • 2013-11-02
    • 2013-02-23
    相关资源
    最近更新 更多