递归加载其他组件的 React Component

React Component that recursively loads other components

所以,我有一个用 wordpress 构建的媒体网站,它使用 react js(我不建议这样做,因为 wordpress 有它自己的做事方式,并不总是与 react 配合得很好)。在这个网站上,我想要一个侧边栏,它可以根据旁边文章的高度动态加载侧边栏的元素(广告、推荐文章、社交媒体按钮等)。这些元素本身就是 React 组件。所以这一切的工作方式,在我看来,文章组件首先被加载到页面上,完成后,componentDidMount,它获取自身的高度并将其发送到侧边栏组件。这部分是如何发生的对我的问题并不重要,但它作为道具 this.props.data.sidebarHeight) 提供给侧边栏组件。侧边栏然后根据该高度创建自己。它这样做,或者它应该这样做,递归地:如果我还剩下这么多space,那么我将放入一个广告组件,然后从我的高度中减去广告组件的高度,然后检查一直到新的高度,直到我没有足够的 space 来添加更多组件(参见 .Bam 动态边栏。这是我的边栏组件的 jsx 代码:

var SidebarComponent = React.createClass({

    recursivelyMakeSidebar: function(height, sidebar) {
        // base case
         if (height < 250 ) {
            return sidebar;
        }
        if (height > 600) {
            sidebar = sidebar + <AdvertisementSkyscraper />;
            newHeight = height - 600;
        } else if (height > 250) {
            sidebar = sidebar + <AdvertisementBox />;
            newHeight = height - 250;
        }
        return this.recursivelyMakeSidebar(newHeight, sidebar);
    },

    render: function() {
        sidebarHeight = Math.round(this.props.data.sidebarHeight);
        currentSidebar='';
        sidebar = this.recursivelyMakeSidebar(sidebarHeight, currentSidebar);
            return (
                <div>
                    {sidebar}
                </div>
            )
        }
    }
);

// render component
React.render(
    <SidebarComponent data={dataStore.sidebar} />,
    document.getElementById('mn_sidebar_container')
);

没用。它将returns[object Object]拖到DOM上。也许我对 react 的理解还不够,但是如果有任何关于如何做到这一点的想法,如果真的可行的话,那就太好了。

这里的根本问题是您将组件连接在一起,就好像它们是 HTML 的字符串一样,但它们实际上是函数。将它们作为函数推入数组即可。在以下示例中,我还将一些比较运算符调整为“>=”,以确保您不会陷入无限循环。

var SidebarComponent = React.createClass({
  recursivelyMakeSidebar: function(height, sidebar) {
    if (height < 250 ) {
        return sidebar;
    }
    if (height >= 600) {
        sidebar.push(<p>600</p>)
        height-=600
    } else if (height >= 250) {
        sidebar.push(<p>250</p>)
        height-=250
    }
    return this.recursivelyMakeSidebar(height, sidebar);
  },
  render:function(){
    var sidebarHeight = Math.round(this.props.data.height);
    var currentSidebar = [];
    var sidebar = this.recursivelyMakeSidebar(sidebarHeight,  currentSidebar)
    return <div>{sidebar}</div>
}
});


var sidebar = {height:900}

// render component
React.render(<SidebarComponent data={sidebar} />, document.body);