2016-08-01 75 views
0

我有一个反应组件,比如说component_1。 而且,我的数组的格式为array_list = [{},{},{},{}]。呈现数组中的多个反应组件

我试图呈现此组件在我的另一个组件,component_2,就像这样:

import component_1 from 'component_1' 
import array_list from 'array_list' 

class component_2 extends Component{ 
    constructor(props){ 
    super(props) 
    } 

    render(){ 
    const {renderMenu} = this.props 
    var contentData = []; 
    array_list.forEach(function(item, index, array){ 
      contentData.push(<component_1 {...item} />); 
    }); 
    return(
     <div> 
     <div className="ui four column centered grid"> 
      {contentData} 
     </div> 
     </div> 
    ) 
    } 
} 

export default component_2 

同时,它通常与其他HTML元素的作品。在这里它会抛出一个错误:

React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components). Check the render method of `OnBoardingContentElement` 

可以渲染反应组件的数组这样吗?如果不是,那么是否有任何规避方法?

回答

0

您确定您的导入声明正在工作吗?同样可以看看array.map,它非常适合将对象数据数组转换为组件数组。

+0

哪个导入语句?我假设你在谈论array_list,它是的,然后答案是否定的,它不会工作。这只是一个sudo代码。我在函数内部创建了array_list。 – nitte93user3232918

+0

不,您的组件导入。如果createElement抱怨null,那么它听起来像你的组件没有被正确导入。 – John

0

这是@ John的回答。

昨晚我遇到了这个确切的问题。这是我在做什么:

// MyComponent.js 

export const MyComponent = (<h1>Hello, world</h1>); 

// index.js 

import { MyComponent } from './MyComponent'; 

React.render((<MyComponent />), document.getElementById('root')); 

你能看到错误吗?它有点微妙。

问题是MyComponent.js未导出React组件。它导出已经实例化的React元素。

@约翰建议这可能是你在做什么。纠正它的最好方法是确保MyComponent.js实际上是导出组件:

// MyComponent.js 

export const MyComponent =() => (<h1>Hello, world</h1>);