简体   繁体   中英

How to pass a function as props to React Children?

I want to pass this handle function to all children's of my Layout component. I know how to do it on custom components but on children I can't get it to work.

I tried the solution from here but I keep getting this warning:

在此处输入图像描述

Here is my code:


function Layout({ preview, children }) {
  
  const [hovered, setHovered] = useState(false);

  function toggleHover() {
    setHovered(!hovered);
  }

  const childrenWithProps = React.Children.map(children, (child) => {
    if (React.isValidElement(child)) {
      return React.cloneElement(child, { toggleHover });
    }
    return child;
  });

  return (
    <>
      <Mouse hovered={hovered} />

      <div>
        <Navbar toggleHover={toggleHover} />
        <main>{childrenWithProps}</main>
        <Footer toggleHover={toggleHover} />
      </div>
    </>
  );
}

export default Layout;

Problem is on function childrenWithProps , especially in React.cloneElement props argument. In your example you are using value toggleHover which essentially transforms into toggleHover: toggleHover .

To make it work you need to transform passed props into this: children_prop_name: toggleHover .

A more detailed example:

Function handling children properties:

const childrenWithProps = React.Children.map(children, (child) => {
  if (React.isValidElement(child)) {
    return React.cloneElement(child, { toggleProp: toggleHover });
  }
  return child;
});

A child component:

function Child({toggleProp}) {
  return <div onHover={toggleProp}>Click</div>
}

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