if-else statement inside jsx: ReactJS

前端 未结 12 1039
广开言路
广开言路 2020-11-22 08:48

I need to change render function and run some sub render function when a specific state given,

For example:

render() {
    return (   
        

        
12条回答
  •  清酒与你
    2020-11-22 09:21

    Simple example of nested loop with if condition in React:

    Data example:

        menus: [
        {id:1, name:"parent1", pid: 0},
        {id:2, name:"parent2", pid: 0},
        {id:3, name:"parent3", pid: 0},
        {id:4, name:"parent4", pid: 0},
        {id:5, name:"parent5", pid: 0},
        {id:6, name:"child of parent 1", pid: 1},
        {id:7, name:"child of parent 2", pid: 2},
        {id:8, name:"child of parent 2", pid: 2},
        {id:9, name:"child of parent 1", pid: 1},
        {id:10, name:"Grand child of parent 2", pid: 7},
        {id:11, name:"Grand child of parent 2", pid: 7},
        {id:12, name:"Grand child of parent 2", pid: 8},
        {id:13, name:"Grand child of parent 2", pid: 8},
        {id:14, name:"Grand child of parent 2", pid: 8},
        {id:15, name:"Grand Child of Parent 1 ", pid: 9},
        {id:15, name:"Child of Parent 4 ", pid: 4},
        ]
    
    

    Nested Loop and Condition:

        render() {
        let subMenu='';
        let ssubmenu='';
        const newMenu = this.state.menus.map((menu)=>{
        if (menu.pid === 0){
        return (
        
    • {menu.name}
        {subMenu = this.state.menus.map((smenu) => { if (menu.id === smenu.pid) { return (
      • {smenu.name}
          {ssubmenu = this.state.menus.map((ssmenu)=>{ if(smenu.id === ssmenu.pid) { return(
        • {ssmenu.name}
        • ) } }) }
      • ) } })}
    ) } }) return (
    {newMenu}
    ); } }

提交回复
热议问题