反应容器道具子传递

时间:2021-02-18 12:28:58

标签: reactjs

怕这个问题简单愚蠢但我卡住了(

我有一个带有一些嵌套组件的 Box 组件:

<Box.Content anyProp="prop">
  <Box.Text...
  <Box.Links

如何将 Box.Content 中的所有道具传递给所有子容器(Box.Text、Box.Links 等)?

尝试不走运:

BoxComponent.Content = (...props) => (
  <BoxContent {...props}>{props.children}</BoxContent>
);

然后尝试从子容器内的父级捕获任何道具 - 未列出道具(

1 个答案:

答案 0 :(得分:1)

您可以使用 React.cloneElement 在其子项上动态设置父项的 props。

运行以下代码片段。 prop1 组件上的 prop2Parent 被传递给 Child1Child2 组件。

const Child1 = (props) => <p>Child 1: {JSON.stringify(props)}</p>;
const Child2 = (props) => <p>Child 2: {JSON.stringify(props)}</p>;

const Parent = ({ children, ...props }) => {
  children = children.map(v => React.cloneElement(v, props));

  return <div id="parent">{children}</div>;
};

const App = () => (
  <Parent prop1="foo" prop2="bar">
    <Child1 />
    <Child2 />
  </Parent>
);

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

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