javascript - React - 将图标添加到组件内的标题

标签 javascript html reactjs redux jsx

我目前正在尝试解决 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')
    }
}

所以我想做的是将多个图标添加到 SalesChannels 页面的 IBox 标记内,而不使 IBox 组件依赖于它。

希望能帮到你。谢谢!

最佳答案

您可以像 children 一样在 props 中传递组件或组件数组

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

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

关于javascript - React - 将图标添加到组件内的标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36700609/

相关文章:

html - 在文档中第一次出现 Table 时定位 <th> 元素

javascript - cookie 值未定义(react-cookie 2.0.6)

javascript - react 不变违规=>不一致

javascript - 区分客户端运行的是 OSX 还是 Windows

javascript - 结合Javascript中几个值的数字范围

c# - jQuery vs. C#:使用主文本框

javascript - Div 动态调整为窗口高度,但在将更多内容添加到 HTML 时失败

javascript - 如何在 Google Chrome 或 Chromium 中触发 "yellow prompt"?

javascript - 从 React.js 向 Node.js API 发出多个请求

javascript - 无法过滤数组以在 react 应用程序上获取电影