【问题标题】:Setting up tabs on state设置状态选项卡
【发布时间】:2019-09-10 23:03:59
【问题描述】:

我正在尝试在父组件状态下设置一个 React 组件的选项卡,类似这样

import React from 'react';
import Component1 from '../myChildComponents/Component1';
import Component2 from '../myChildComponents/Component2';
import Component3 from '../myChildComponents/Component3';

class ParentComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      tabs: [
        {id: '1', text: 'Tab 1', component: Component1},
        {id: '2', text: 'Tab 2', component: Component2},
        {id: '3', text: 'Tab 3', component: Component3},
      ]
    }
  }
  
  render() {
    return (
      <!-- All the other stuff goes here, like the tabs headers -->
      <TabContent>
      {
        this.state.tabs.map((t, i) => 
          <TabPane key={i} tabId={t.tabId}>
            <t.component {...this.props.data}>
          </TabPane>
        )
      }
      </TabContent>
    )
  }
}

这样的事情可以实现吗?我已经尝试过使用React.createComponent 函数,但这有效

Edit1:已更新以反映当前的测试实现,但仍会在控制台上看到以下消息

未捕获(承诺)不变违规:元素类型无效: 期望一个字符串(对于内置组件)或一个类/函数(对于 复合组件)但得到:未定义。您可能忘记导出 你的组件来自它定义的文件。检查渲染方法

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案1】:

    是的,你可以使用这样的组件。

     render() {
        return (
          <!-- All the other stuff goes here, like the tabs headers -->
          <TabContent>
          {
            this.state.tabs.map((t, i) => 
              <TabPane key={i} tabId={t.tabId}>
                <t.component {...t.data}/>
              </TabPane>
            )
          }
          </TabContent>
        )
      }
    

    唯一需要改变的是:

    • 你的对象键是component;小写
    • 您需要使用 t.data 对象上的扩展运算符来设置道具:{...t.data}

    【讨论】:

    • 好吧,我试着这样做,用大括号,将预期的组件包围起来,我得到了Uncaught (in promise) Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it's defined in. Check the render method
    • 没有卷曲的后备箱 ({id: '1', text: 'Tab 1', component: component1, data: {props.data1}}) 得到了Uncaught (in promise) Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in. Check the render method
    • @CJLopez 删除 {props.data1}、data2 和 data3 等周围的花括号
    • 应该是{id: '1', text: 'Tab 1', component: {component1}, data: props.data1}
    • Aaaaand... 出乎意料的是,它开始像您提到的那样工作。将您的答案标记为正确答案。谢谢!
    猜你喜欢
    • 2020-01-19
    • 2016-06-30
    • 1970-01-01
    • 1970-01-01
    • 2017-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多