importRowListfrom'./RowList.js';exportdefaultfunctionApp(){return(<RowList><p>This is the first item.</p><MoreRows/></RowList>);}functionMoreRows(){return(<><p>This is the second item.</p><p>This is the third item.</p></>);}
无法获取内部组件(例如 <MoreRows />)的渲染输出,当操作 children 时。这就是为什么 通常最好使用其中一种替代方案。
为每个子元素运行一些代码
调用 Children.forEach 来迭代 children 数据结构中的每个子元素。它不返回值,类似于 数组 forEach 方法。 你可以使用它来运行自定义逻辑,例如构建你自己的数组。
import{Children}from'react';exportdefaultfunctionSeparatorList({children}){constresult = [];Children.forEach(children,(child,index)=>{result.push(child);result.push(<hrkey={index}/>);});result.pop();// Remove the last separatorreturnresult;}
import{Children}from'react';exportdefaultfunctionRowList({children}){return(<divclassName="RowList"><h1className="RowListHeader">
Total rows: {Children.count(children)}</h1>{Children.map(children,child=><divclassName="Row">{child}</div>)}</div>);}
import{RowList,Row}from'./RowList.js';exportdefaultfunctionApp(){return(<RowList><Row><p>This is the first item.</p></Row><Row><p>This is the second item.</p></Row><Row><p>This is the third item.</p></Row></RowList>);}
import{RowList,Row}from'./RowList.js';exportdefaultfunctionApp(){return(<RowList><Row><p>This is the first item.</p></Row><MoreRows/></RowList>);}functionMoreRows(){return(<><Row><p>This is the second item.</p></Row><Row><p>This is the third item.</p></Row></>);}
import{RowList,Row}from'./RowList.js';exportdefaultfunctionApp(){return(<RowListrows={[{id:'first',content:<p>This is the first item.</p>},{id:'second',content:<p>This is the second item.</p>},{id:'third',content:<p>This is the third item.</p>}]}/>);}
importTabSwitcherfrom'./TabSwitcher.js';exportdefaultfunctionApp(){return(<TabSwitchertabs={[{id:'first',header:'First',content:<p>This is the first item.</p>},{id:'second',header:'Second',content:<p>This is the second item.</p>},{id:'third',header:'Third',content:<p>This is the third item.</p>}]}/>);}
与将子元素作为 JSX 传递不同,这种方法允许您将一些额外的数据(如 header)与每个项目关联。因为您直接使用 tabs,并且它是一个数组,所以您不需要 Children 方法。
importTabSwitcherfrom'./TabSwitcher.js';exportdefaultfunctionApp(){return(<TabSwitchertabIds={['first','second','third']}getHeader={tabId=>{returntabId[0].toUpperCase() + tabId.slice(1);}}renderContent={tabId=>{return<p>This is the {tabId} item.</p>;}}/>);}
import{RowList,Row}from'./RowList.js';exportdefaultfunctionApp(){return(<RowListrowIds={['first','second','third']}renderRow={(id,index)=>{return(<RowisHighlighted={index % 2 === 0}><p>This is the {id} item.</p></Row>);}}/>);}