2016-04-18 16 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

相关问题