简体   繁体   English

反应递归的多级下拉列表

[英]multilevel dropdown for react recursion

I am building a multilevel menu and want to use recursion to display the menu. 我正在构建一个多级菜单,并希望使用递归来显示菜单。 Something like the multi-level dropdown from here . 喜欢的东西从多层次的下拉这里

In my code my menu looks like this. 在我的代码中,我的菜单看起来像这样。

const menu = [
  {
    name: 'Man Utd',
    menu: [
       {
          name: 'Stadium'
       },
       {
          name: 'About'
       }
    ]
  },
  {
    name: 'Liverpool',
    menu: [
       {
           name: 'Contact'
       }
    ]
  }
];

which I then pass this into my react component. 然后我将其传递给我的反应组件。

const Dropdown = ({ menu }) => {
    const renderMenu = (items) => {
        return items.map((item: any, index: any) => {
            return (
                <div>
                    {item.menu ? renderMenu() : item.name}
                </div>
            )
        })
    }

    return (renderMenu(menu));
}

the issue here is that it is causing an infinite loop. 这里的问题是它导致无限循环。

Can anyone advise me as to how I can improve this? 任何人都可以告诉我如何改善这一点?

You need to pass item.menu as argument to renderMenu when you recursively render the menu. 递归渲染菜单时,需要将item.menu作为参数传递给renderMenu

Example

 const menu = [ { name: "Man Utd", menu: [ { name: "Stadium" }, { name: "About" } ] }, { name: "Liverpool", menu: [ { name: "Contact" } ] } ]; const Dropdown = ({ menu }) => { const renderMenu = items => { return items.map((item: any, index: any) => { return ( <div style={{ marginLeft: 10 }}> {item.name} {item.menu ? renderMenu(item.menu) : null} </div> ); }); }; return <div>{renderMenu(menu)}</div>; }; ReactDOM.render(<Dropdown menu={menu} />, document.getElementById("root")); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div> 

Your not passing down anything to renderMenu. 你没有把任何东西传递给renderMenu。 You should call renderMenu(item.menu) 你应该调用renderMenu(item.menu)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM