亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 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 關注
  • 198 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號