2016-04-18 19 views
1

我目前正試圖解決一個反應問題。
我希望能夠將圖標添加到名爲SalesChannels的容器。 這裏是代碼的salesChannels頁:(JSX)react - 將圖標添加到組件內的頭部

import React, { Component } from 'react'; 
import PageContent from 'components/PageContent'; 
import IBox from 'components/IBox'; 

export default class SalesChannelsPage extends Component { 
    constructor(props) { 
     super(props); 

     this.state = { 
      rows: [] 
     } 
    } 

    render() { 
     return (
      <PageContent header="Salgskanaler"> 
       <IBox title="Salgskanaler"> 

       </IBox> 
      </PageContent> 
     ); 
    } 
} 

正如你所看到的,我已經添加了一個名爲IBOX組件。這應該是可重複使用的 它看起來像這樣:

import React, {Component} from 'react'; 
import IBoxTools from './IBoxTools' 

export default class IBox extends Component { 
    render() { 
     return(
      <div className="ibox"> 
       <div className="ibox-title"> 
        {this.props.title} 

       //this is where the icon should be rendered in the dom 

       </div> 
       <div className="ibox-content"> 
        {this.props.children} 
       </div> 
      </div>  
     ); 

    } 
} 

我也創造了另一個組件調用IBoxTools - 這包含實際的圖標/「我」的標籤:

import React, {Component} from 'react'; 

export default class IBoxTools extends Component { 
    render() { 
     let icon; 

     if(this.props.icon) { 
      icon = (
       <a title={this.props.title}> 
        <i onClick={() => this.iconClicked()} className={`pull-right ${this.props.icon}`}></i> 
       </a> 
      ); 
     } 

     return icon; 
    } 

    iconClicked() { 
     console.log('icon clicked') 
    } 
} 

那麼我試圖do是將多個圖標添加到IBox標籤內的SalesChannels頁面,而不使IBox組件依賴於它。

我希望你能幫上忙。謝謝!

回答

0

您可以通過組件的組件或陣列中的道具,就像children

<IBox 
    title="Salgskanaler" 
    icons={[ 
    <IBoxTools key="icon1" icon="foo" />, 
    <IBoxTools key="icon2" icon="bar" /> 
    ]} 
> 
    {/* normal children here */} 
</IBox> 

內。然後IBox你寫{ this.props.icons }這會使圖標(或任何其他)如果你通過它..否則,會顯示如果道具是未定義的,則不做任何事

+0

真棒,謝謝,它工作! :) – PatrickGoethe

0

如果您不想每次都顯示圖標,則可以使用條件。如果我理解你正在試圖做什麼...

import React, {Component} from 'react'; 
import IBoxTools from './IBoxTools' 

export default class IBox extends Component { 
    render() { 
     return(
      <div className="ibox"> 
       <div className="ibox-title"> 
        {this.props.title} 

       //this is where the icon should be rendered in the dom 
       {(condition) ? <IBoxTools /> : ""} 

       </div> 
       <div className="ibox-content"> 
        {this.props.children} 
       </div> 
      </div>  
     ); 

    } 
} 

或者,如果你需要多次這樣做,就像你說的,那麼我會使用具有地圖功能underscore.js或類似的東西。

{_.map(icons, function(icon) { 
    return (
     <IBoxTools /> 
    ) 
})} 

或兩者的某種組合。

+0

普通JavaScript有一個'map'函數https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map – azium

+0

非常感謝你的回答! :) – PatrickGoethe

相關問題