2017-06-21 44 views
0

我想開發一個簡單的TabsLayout組件。此組件顯示標題中的所有標籤,以及與選定標籤關聯的內容。自定義組件作爲我的組件的孩子在React

我想一個部件,其中用戶可以導入e將孩子的組件這樣的例子:

 <TabsLayout tabs={["Description","Flow","History"]} selected="Description"> 
      <X tab="Description"/> 
      <Y tab="Flow"/> 
      <Z tab="History"/> 
     </TabsLayout> 

在這種情況下,X是可見的,並且Y和Z是隱藏的。所以gol只提供了一個名爲Tabslayout的簡單組件,沒有回調。我不能undestrand如何渲染這個例子中的孩子becase X,Y,X(例如一些div或一些語義UI組件不渲染。

回答

0

您需要在製表符之前篩選出它們。工作示例。

const TabsLayout = ({tabs, selected, onSelect, children}) => (
 
    <div> 
 
    {tabs.map((t) => 
 
     selected === t 
 
     ? <b>{t} </b> 
 
     : <a href="#" onClick={() => onSelect(t)}>{t} </a>) 
 
    } 
 
    <div>  
 
     {React.Children.toArray(children).filter(({props}) => selected === props.tab)} 
 
    </div> 
 
    </div> 
 
); 
 

 
const X = ({tab}) => <div>X: {tab}</div>; 
 
const Y = ({tab}) => <div>Y: {tab}</div>; 
 
const Z = ({tab}) => <div>Z: {tab}</div>; 
 

 
let selected = 'Description'; 
 
function handleSelection(tab) { 
 
    selected = tab; 
 
    renderTabs(); 
 
} 
 

 
function renderTabs() { 
 
    ReactDOM.render(
 
    <TabsLayout 
 
     tabs={["Description","Flow","History"]} 
 
     selected={selected} 
 
     onSelect={handleSelection} 
 
    >  
 
     <X tab="Description"/> 
 
     <Y tab="Flow"/> 
 
     <Z tab="History"/> 
 
    </TabsLayout>, 
 
    document.getElementById('app') 
 
); 
 
} 
 

 
renderTabs();
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 

 
<div id="app"></div>

0

感謝所有人的幫助,但我找到了解決方案。 簡單地說,我叫

回報this.props.children.find((子)=> child.props.tab === this.state.selected);

where state.selected selected我在打開這個問題時選擇了TabsLayout。

相關問題