为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 React 中将 prop 传递给 {children}?

如何在 React 中将 prop 传递给 {children}?

函数式编程 2023-07-14 15:35:55
我有一个父组件,充当其子组件的包装器。如何将道具传递给将使用以下格式渲染的子项?import React, { useEffect, useState } from 'react';const Parent = ({ children }) => {  const [completeState, setCompleteState] = useState(false);  useEffect(    () => {      /* .. code that runs then sets completeState to true */    setCompleteState(true);     }, []  );  return (     <section>       /*           how to pass a 'didComplete' prop to children?           didComplete={completeState}       */       {children} // Child component below would be rendered here with the didComplete prop passed in    </section>  )}import React from 'react';const Child = ({ didComplete }) => (<h1>The function completed? {didComplete}</h1>); 
查看完整描述

1 回答

?
临摹微笑

TA贡献1982条经验 获得超2个赞

它props.children是一个 React Element,它只不过是一个普通的 JS 对象,具有需要在 DOM 中呈现的内容的描述。


为了提供其他详细信息,我们需要克隆现有的 React Element 对象并提供其他详细信息。


为此,我们可以使用React.cloneElementAPI 将附加属性传递给children:


return (

     <section>

       {React.cloneElement(children, {didComplete: completeState})}

    </section>

);


查看完整回答
反对 回复 2023-07-14
  • 1 回答
  • 0 关注
  • 133 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信