Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
137 views
in Technique[技术] by (71.8m points)

javascript - React parent function doesn't receive child parameters

I'm facing a strange problem.

I created my function copy in my parent component.

const copy = (field, menu) => {
    console.log({ field, menu, localMetaSpec });

    localMetaSpec.menus[menu.id].elements.splice(
        localMetaSpec.menus[menu.id].elements.length,
        0,
      { ...field, id: uuid() }
    );
    return localMetaSpec;
};

Then I gave it to my child component, and I called it like this

[...]
case 'copy':
     return (
         <Tooltip title='Copy'>
             <IconButton
               aria-label='copy'
               onClick={() => {
                 console.log(field);
                 console.log(menu);
                 actions.copy(field, menu);
               }}
             >
             <FileCopyIcon />
         </IconButton>
     </Tooltip>
    );
[...]

As you can see in the console, field and menu are objects, but when received as a parameter in the function they become undefined. enter image description here

Why this is happening?

question from:https://stackoverflow.com/questions/65844798/react-parent-function-doesnt-receive-child-parameters

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Well, the problem was from the parent component where I called the child one :

<Menu
  actions={{
    copy: () => copy(),
    delete: () => deleteElement(),
  }}
  classes={classes}
  elements={elements}
  key={menu.id}
  menu={menu}
/>

I wasn't passing the parameter through the original function. So I did that :

<Menu
  actions={{
    copy: (fieldParam, menuParam) => copy(fieldParam, menuParam),
    delete: () => deleteElement(),
  }}
  classes={classes}
  elements={elements}
  key={menu.id}
  menu={menu}
/>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...