害怕这个问题很简单愚蠢,但我卡住了 (
我有一些嵌套的盒子组件:
<Box.Content anyProp="prop">
<Box.Text...
<Box.Links
如何将所有道具形式 Box.Content 传递给所有子容器(Box.Text,Box.Links,其他任何东西)?
没有运气的尝试:
BoxComponent.Content = (...props) => (
<BoxContent {...props}>{props.children}</BoxContent>
);
然后尝试从子容器内的 Parent 捕获任何道具-没有列出道具(
您可以使用React.cloneElement
动态设置父对象在其子对象上的道具。
运行以下代码段。Parent
组件上的prop1
和prop2
将传递给Child1
和Child2
组件。
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="s://cdnjs.cloudflare/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="s://cdnjs.cloudflare/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="s://unpkg/babel-standalone@6/babel.min.js"></script>
<div id="root"></div>
本站系公益性非盈利分享网址,本文来自用户投稿,不代表边看边学立场,如若转载,请注明出处
评论列表(37条)