react-将图标添加到组件内部的标题中

react - add icons to header inside component

本文关键字:内部 标题 组件 图标 添加 react-      更新时间:2023-09-26

我目前正在尝试解决一个react问题
我希望能够将图标添加到名为SalesChannels的容器中。这是salesChannels页面的代码:(JSX)

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的组件,它包含实际的图标/"i"标签:

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')
    }
}

因此,我想做的是在IBox标签内的SalesChannels页面中添加多个图标,而不使IBox组件依赖于它

我希望你能帮忙。谢谢

您可以像children 一样传递道具中的组件或组件数组

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

然后在IBox中编写{ this.props.icons },如果传入它,它将呈现图标(或其他任何东西)。否则,如果道具未定义,它将不显示任何内容。

如果不想每次都显示图标,可以使用一个条件。如果我理解你的意图。。。

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函数的东西。

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

或者两者的结合。