[英]Passing an array of Components as a Props in React
我正在尋找一種將組件數組傳遞給選項卡組件的道具的方法。 只是想知道這是否可能。
所以我需要創建一個組件來縮短 Material ui 的 tabbing 方法,但我找不到一種方法來傳遞組件數組作為 prop 以便它會在該組件上呈現。
這是我的代碼示例:
<FullWidthTab
components = [<Component1/>, <Component2/>] //this is where components renders
menuLabels = ['Menu1', 'Menu2'] //this is where title render
/>
我像這樣將它們映射到我的代碼上,並使用了 lodash map 方法:
map(components, component=>{
<TabContainer>{component}</TabContainer>
}
但它返回這個。 警告:react-swipeable-view:提供的孩子之一無效:null。 我們期待一個有效的 React 元素
當我console.log
組件返回:{$$typeof: Symbol(react.element), type: ƒ, key: null, ref: null, props: {...}} Object Need help
我希望它可以渲染組件。
因為您需要在地圖中返回一個值。
map(components, component=>{
return <TabContainer>{component}</TabContainer>
}
組件的名稱必須以大寫字母開頭,但是我在這里可以看到, components = [<component1/>, <component2/>]
不是。 因此,您必須將[<component1/>, <component2/>]
為[<Component1/>, <Component2/>]
。 第二件事,我看到您的map
語法很奇怪,它一定是這樣的:
components.map(component => (<TabContainer>{component}</TabContainer>))
參考: https : //reactjs.org/docs/jsx-in-depth.html#user-defined-components-must-be-capitalized
您的es6語法需要進行細微調整才能返回react組件。
map(components, component => <TabContainer>{component}</TabContainer> )
或者,如果您可以使用數組中的map函數而不是從庫中導入。
components.map( component => <TabContainer>{component}</TabContainer> )
我用另一個實現解決了這個問題。
我使用了“ react-swipeable-views”,而是傳遞了一個我用過的組件
<SwipeableViews
axis={theme.direction === 'rtl' ? 'x-reverse' : 'x'}
index={this.state.value}
onChangeIndex={this.handleChangeIndex}
>
{ children }
</SwipeableViews>
並更改:
<FullWidthTab
components = [<Component1/>, <Component2/>] //this is where components renders
menuLabels = ['Menu1', 'Menu2'] //this is where title render
/>
至
<FullWidthTab
components = [<Component1/>, <Component2/>] //this is where components renders
menuLabels = ['Menu1', 'Menu2'] //this is where title render
>
<Component1/>
<Component2/>
</FullWidthTab>
但是,如果您可以獲得如何通過道具傳遞組件的話,那就太好了!
我認為您必須將FullWidthTab數組上的組件作為節點值傳遞:
<FullWidthTab
components = [component1, component2] //this is where components renders
MenuLabels = ['Menu1', 'Menu2'] //this is where title
render
/>
您的地圖繼續原樣。
如果這不起作用,請嘗試在地圖內渲染組件。 將組件作為FullWidthTab的節點傳遞,然后呈現它:
map(components, component=>{
<TabContainer>{<component/>}</TabContainer>
}
注意:此代碼未經測試!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.