猿问

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

我有一个父组件,充当其子组件的包装器。如何将道具传递给将使用以下格式渲染的子项?


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>); 


函数式编程
浏览 173回答 1
1回答

临摹微笑

它props.children是一个 React Element,它只不过是一个普通的 JS 对象,具有需要在 DOM 中呈现的内容的描述。为了提供其他详细信息,我们需要克隆现有的 React Element 对象并提供其他详细信息。为此,我们可以使用React.cloneElementAPI 将附加属性传递给children:return (&nbsp; &nbsp; &nbsp;<section>&nbsp; &nbsp; &nbsp; &nbsp;{React.cloneElement(children, {didComplete: completeState})}&nbsp; &nbsp; </section>);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答