【问题标题】:How to pass child object to parent when the save button in parent is clicked?单击父项中的保存按钮时如何将子对象传递给父项?
【发布时间】:2020-07-14 12:24:17
【问题描述】:

我有父组件和多个子组件。每个子组件负责获取数据并绑定到本地存在的对象。

现在在父组件中,我有保存方法。当触发保存点击事件时,我需要从孩子收集所有对象并映射到单个对象并传递给 api。任何人都可以帮助我如何做到这一点?

下面给出了我尝试过但未能成功的一些方法。我在这里使用了 useRef。

// One of the child component 
const Questionnaire =  forwardRef((props,ref) => {
  useImperativeHandle(ref, () => ({
        getUserEnteredObjectRef() {
            return userEnteredData;
        }
    }));
});

//in my parent 

function HandleSaveRequest() {
     console.log('Save Request Command:');
     let qtnObj = questionnaireRef.current.getUserEnteredObjectRef(); // prints the object
     console.log(qtnObj); // displays the object from the child
     setSaveRequestObj({qtn:qtnObj}); // don't get assigned and the object will be empty. strange is when i click the save 2nd time i get the object assigned.
     axios.post(API, SaveRequestObj).then(res => {
       goToDashboard();
     }).catch(err => {
       console.log('Error while saving' + err.message);
     });
  }

参考 Call child method from parent

【问题讨论】:

  • 您是否需要在按保存时收集数据,或者在每个子组件上都有一个 onChange 回调更有意义?如果每个组件都有一个 onChange 回调,那么父组件可以在提交之前构建对象以保存,而不是在提交时保存。
  • @NickHoward 这是我的最后一个选择,但是当我点击保存时,我试图仅检索子对象

标签: reactjs redux react-redux react-hooks


【解决方案1】:

refs doc:

你需要使用current来访问getUserEnteredObjectRef

let qtnObj = questionnaireRef.current.getUserEnteredObjectRef(); 

See a demo here

【讨论】:

  • 是的!我正在使用“当前”,抱歉我之前错过了它,但是当我将它设置为使用状态变量时,我看不到被分配。但是我观察到的奇怪的事情是,当我两次单击保存按钮时,对象被分配给使用状态变量
猜你喜欢
  • 2021-05-09
  • 2020-12-17
  • 2018-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多