使用组件名称动态地进行反应

时间:2018-02-15 23:19:53

标签: reactjs

我收到以下错误:

Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component />

外部组件

import Comment from 'material-ui-icons/Comment'
import Attachment from 'material-ui-icons/Attachment'
import History from 'material-ui-icons/History'
import TrendingUp from 'material-ui-icons/TrendingUp'

        this.components = {
            comment: Comment,
            attachment: Attachment,
            history: History,
            trendingup: TrendingUp
        }

渲染:

                {this.menu.map((data, index) => (
                <span key={index}>
                    {dynamicClassName = this.state[data.value.class]}

                    <span
                        key={index}
                        id="historicalTestsColorBandTitle"
                        className={"mobileBottomBannerOptions "+dynamicClassName}
                        onClick={this.handleBannerOptionsClick.bind(this, data.value.type)}
                    >

                        {DynamicComponentName = this.components[data.value.icon]}

                        {!dynamicClassName &&
                        <div>
                            <table><tbody><tr>
                                <td>
                                    <DynamicComponentName
                                        className="mobileBottomBannerIcon"
                                    />
                                </td>
                            </tr></tbody></table>
                        </div>
                        }

                        {dynamicClassName &&
                        <div>
                            <table><tbody><tr>
                                <td>
                                    <DynamicComponentName
                                        className="mobileBottomBannerIcon"
                                    />
                                </td>
                                <td className="menuOptionTitle">
                                    {data.value.name}
                                </td>
                            </tr></tbody></table>
                        </div>
                        }
                    </span>
                </span>
            ))}

您可以看到&#39; DynamicComponentName&#39;是创建组件名称的位置。我需要使用这样的方法,因为这些组件的顺序会根据最后一次单击而改变。

组件显示正常但我在顶部收到错误消息...

有关如何解决错误消息的任何建议吗?

三江源!

1 个答案:

答案 0 :(得分:2)

您需要将作业移出JSX:

render() {
  const dynamicClass = this.state[data.value.class];
  const DynamicComponent = this.components[data.value.icon];

  return // ...
}

如果您需要在map内进行作业,您也可以这样做:

this.menu.map((data, index) => {
  const dynamicClass = this.state[data.value.class];
  const DynamicComponent = this.components[data.value.icon];

  return // ...
})