如何将函数作为道具传递给 React Children?

How to pass a function as props to React Children?

我想将此句柄函数传递给布局组件的所有子项。我知道如何在自定义组件上执行此操作,但在 children 上我无法使用它。

我尝试了 的解决方案,但我不断收到此警告:

这是我的代码:


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;

function Mouse({hovered}) {
  return null;
};

function Navbar({toggleHover}) {
  return <div onMouseEnter={toggleHover}>Hover on me</div>
};

function Footer({toggleHover}) {
  return <div onMouseEnter={toggleHover}>Hover on me</div>
};

function Child({toggleHover}) {
  return <div onMouseEnter={toggleHover}>I am child, hover on me</div>
};

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

  function toggleHover() {
    console.log("hovered");
    setHovered(!hovered);
  }

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

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

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

function Parent() {
  return (
    <div>
      <Layout>
        <Child />
        <Child />
        <Child />
      </Layout>
    </div>
  )
}

const rootElement = document.getElementById("root");
ReactDOM.render(
  <Parent />,
  rootElement
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>

<body>
    <div id="root"></div>
</body>

问题出在函数 childrenWithProps 上,尤其是在 React.cloneElement props 参数中。在您的示例中,您使用的值 toggleHover 基本上转换为 toggleHover: toggleHover.

要使其正常工作,您需要将传递的道具转换为:children_prop_name: toggleHover

更详细的例子:

处理子属性的函数:

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

一个子组件:

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