2017-01-10 28 views
0

更新:在发布原始问题后,我发现我的RequireJS项目存在依赖问题,导致问题。这个问题与React无关。不能调用React组件递归

可以嵌套/递归调用组件,我是问路。将这个Codepen demo看作概念证明。


我试图做一个通用组件,它接受一个对象,并呈现基于对象的type另一个组件。任何组件都可以调用这个通用组件来让它适当地渲染对象。

class Elem extends React.Component { 
    constructor() { super(); } 

    render() { 
     if (this.props.item.type === 'row') { 
      return <Row item={this.props.item} />; 
     } 
     else if (this.props.item.type === 'col') { 
      return <Col item={this.props.item} />; 
     } 
     else if (this.props.item.type === 'btn') { 
      return <Button item={this.props.item} />; 
     } 
     // else if.... for an arbitrary number of types 
    } 
} 

在这种情况下,它可以产生行和列的网格,等等。每种类型都有自己的HTML结构和一组基于项目需求的类。

的问题是,格列(例如)可能包含嵌套行,或按钮,或其他任何<Elem/>如何呈现。理想情况下,我会避免通过定义<Col/>这样重复自己:

class Col extends React.Component { 
    constructor() { super(); } 

    render() { 
     return (
      <div className="column"> 
       {this.props.item.contents.map(item => { 
        // Item could be a row, button, or something else, so let <Elem> figure it out: 
        return <Elem item={item} />; 
       })} 
      </div> 
     ); 
    } 
} 

,我将通过我的所有对象来<Elem/>整个项目。例如,<Button/>可能会呈现多个位置,但我只定义了一次。

不幸的是抛出一个错误:Uncaught ReferenceError: Col is not definedElem.render。我猜这是因为我通过调用它所调用的子进程中的父进程来嵌套组件。

Codepen demo —取消注释行23看到错误。

如何制作像<Elem/>这样的通用组件,我可以在应用程序的任何位置调用,即使它已经是链的一部分?另外,如何在网格内和网格外渲染按钮/表格/其他组件,而无需在两个地方定义这些组件?

对于它的价值,这是一个web应用程序,我没有使用助焊剂/终极版的/ etc。

+0

听起来像'Link'可能对你有意思 – Icepickle

+1

没有冒犯,但是如果我把'Col'改成'Column'它在你的codepen里面工作,这个类也被命名为'Column' – Icepickle

+1

protip:React仍然只是JSX中的JavaScript和React组件“标签”仍然只是普通的JavaScript对象,所以你可以这样做:'let Type = undefined; switch(this.props.item.type){case(...)Type = Row;打破;案件....; }返回' - 使代码更容易维护,并且可以让您使用Type中的内容比使用列出的代码更容易地调试错误。 –

回答