【问题标题】:Rendering dynamic tabs with React.js and Semantic UI React使用 React.js 和 Semantic UI React 渲染动态选项卡
【发布时间】:2018-05-22 17:13:27
【问题描述】:

使用React.jsSemantic UI React 我想动态创建标签。

当使用const 表示选项卡对象数组时,这可以正常工作。

const panes = [
            {
                menuItem: 'Record 1',
                render: () => <Tab.Pane>Tab 1 Content</Tab.Pane>
            }
        ]
...
<Tab panes={panes}/>

但是,我需要根据状态变量source动态添加这些:

getPanes() {
        return this
            .state
            .source
            .map((source) => [{
                menuItem: source.sourceName,
                render: () => <Tab.Pane>Tab 1 Content</Tab.Pane>
            }])
    }
...
<Tab panes={this.getPanes}/>

这会导致:

Warning: Failed prop type: Invalid prop `panes` of type `function` supplied to `Tab`, expected an array.

【问题讨论】:

    标签: javascript reactjs semantic-ui-react


    【解决方案1】:

    两个问题:

    1. this.getPanes 指的是你的函数定义,它不会调用 你的功能。你想要你的函数的结果,如果你 应该使用括号调用它:this.getPanes()
    2. .map() 返回一个新的元素数组,这是将您提供的函数应用于每个原始元素的结果。您真正想要在.map 中返回的是您的窗格对象,而不是一个窗格对象的数组:

    --

    .map((source) => ({ 
      menuItem: source.sourceName, 
      render: () => <Tab.Pane>Tab 1 Content</Tab.Pane> 
    }))
    

    【讨论】: