1

我正在尝试使用 {children} 将道具传递给子组件。

父组件:

const FatherComp = ({ children, propsToPassToChild }) => (
    <div>Dynamic component content: 
        {children}
    </div>
)

子组件:

const ChildComp = ({ childProps }) => <p>This is the dynamic content</p>

像这样使用它们:

<FatherComp>
    <ChildComp/> // childProps cannot be passed here since it's inside FatherComp
</FatherComp>

我想将来自 FatherComp 的道具(propsToPassToChild)直接传递给 ChildComp:

const FatherComp = ({ children, propsToPassToChild }) => (
    <div>Dynamic component content: 
        >>>>> {children} <<<<< *passing the props somewhere here* 
    </div>
)

是否有可能在没有状态管理的情况下直接对功能组件做出反应?

谢谢!

4

2 回答 2

0

是的,您需要执行以下操作:

<FatherComp>
    <ChildComp name="John" age="21"/>
</FatherComp>

const FatherComp = (props) => (
  <div>Dynamic component content: 
      {props.children}
  </div>
)

接受 propsFatherComp并用于{props.children}渲染父组件内的所有子组件。

于 2021-11-15T17:38:39.920 回答
0

你应该使用render props

参考:https ://reactjs.org/docs/render-props.html#gatsby-focus-wrapper

于 2021-11-15T17:46:38.607 回答