简体   繁体   中英

How to send pass function as props to child component

I have a parent component and some child components and I want send function from parent to child and in child component call it.

parent:

const buttons = [
    {
      key: 'driveFormulaButton',
      title: 'Drive Formula',
      icon: faGitAlt,
      type: 'primary',
      function: (message) => {
        console.log('fasf');
      },
    },
  ];

  return (
      <Child
        buttons={buttons}
      ></Child>
  );

Child Component:

const Child = (props) => {
      return (
          <Button size="small" type={props.buttons.type} onClick={props.buttons.function('test')}> //not work after set propery
            <FontAwesomeIcon icon={props.buttons.icon} />
          </Button>
      );
    });

You call the function instead of passing it an onClick callback and you should map the buttons array:

const Child = (props) => {
  return props.buttons.map((prop) => (
    <Button
      key={prop.key}
      size="small"
      type={prop.type}
      onClick={() => prop.function("test")}
    >
      <FontAwesomeIcon icon={prop.icon} />
    </Button>
  ));
}

Your parent component needs to map through the children components:

Parent

function renderChildren() {
  const buttons = [];   // <--- populate this as in your OP

  return buttons.map((button) => {
    return (
      <Button size="small" type={button.type} onClick={() => button.function('test')}>
        <FontAwesomeIcon icon={button.icon} />
      </Button>
    )
  })
}

return (
  <>
    {renderChildren()}
  </>
);

Well you send an array of buttons as props to you single Child-Component. Then you try to access a single object of that array in the Button-Component. This cant work. Better map throught you button in the parent and send a single button down as props:

  const buttons = [{*Button1*, *Button2*}]

  render(
    {buttons.map((button) => <Child button={button}>)}
  )

Then you can access the button as you intend to in your Child-component.

Next time you ask a question please provide better information to what you are actually trying to do and what the problem (eg error message) is. Ask specific questions. This makes it easier to answer you.

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