代码之家  ›  专栏  ›  技术社区  ›  four-eyes

将道具向下传递给子组件,而不导入子组件

  •  0
  • four-eyes  · 技术社区  · 5 年前

    我有这样一个组件:

    const Foo = ({ size ) => {
        return <Bar size={size}>
            {children}
        </Bar>
    

    然后我用 <Foo /> <AnotherComponent />

    const AnotherComponent = () => {
        <Foo size='gigantic'>
            <WhatEverest />
        <Foo />
    

    然后我想使用 size 道具,传给 <Foo/> 在里面 < 可供其子级使用,而无需将其显式传递给 <WhatEverest /> .

    有办法编辑吗 <Foo/>

    3 回复  |  直到 5 年前
        1
  •  1
  •   Martin    5 年前

    Foo的实现可以向子对象添加任意数量的属性:

    const Foo = ({ size, children }) => {
      return (
        <Bar size={size}>
          {
            React.Children.map(children, (element) => React.cloneElement(element,{size}))
          }
        </Bar>
      );
    }