无法递归调用React组件

时间:2017-01-10 19:18:52

标签: javascript reactjs

更新: 在发布原始问题后,我发现我的RequireJS项目存在导致问题的依赖性问题。该问题与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 defined处引发了错误:Elem.render。我猜这是因为我通过从它调用的子进程中调用父进程来嵌套组件。

Codepen demo - 取消注释第23行以查看错误。

如何在应用中创建一个类似<Elem/>的通用组件,我可以在任何地方调用,即使它已经是链的一部分了?或者,如何在网格内部和外部渲染按钮/表格/其他组件,而不必在两个位置定义这些组件?

对于它的价值,这是一个网络应用程序,我没有使用Flux / Redux /等。

1 个答案:

答案 0 :(得分:1)

您正在寻找&#34; higher-order component&#34;。